Board.objects.annotate(execs=Sum(top__active__value))
gives me a QuerySet
with sums added as annotations (i.e execs
). I am trying to figure out how to add a constant to the summation. That is, the sum of values in the specified columns added to, say, β3
β becomes the annotation. How do I do that?
Annotations and aggregations support the basic numeric operations in the annotation expression.
e.g: Board.objects.annotate(execs=Sum(top__active__value)+3)
That is not working in my scenario:
Board.objects.get(pk=staff_id)
.deptfk.members.filter(active__exact=True)
.order_by("reference")
.prefetch_related("memberpoints")
.annotate(
score=Sum(
"memberpoints__taskfk__value",
filter=Q(memberpoints__managerfk__id__exact=staff_id),
) + 3
)
The above gives me:
TypeError: unsupported operand type(s) for +: 'Q' and 'int'
Without the filter, it works but I need the filter
Iβm not at my computer, so Iβm winging this. Two ideas come to mind -
- wrap the
Sum
clause in a set of parens- e.g.
.annotate(score=(Sum(β¦))+3)
- e.g.
- calculate the sum in a subsequent annotate.
- e.g.
.annotate(score=β¦).annotate(score3=F(βscoreβ)+3)
- e.g.
1 Like
Thanks. It is working now. Much appreciated