Adding constants to Annotations

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)

See Query Expressions | Django documentation | Django

That is not working in my scenario:

            ) + 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)
  • calculate the sum in a subsequent annotate.
    • e.g. .annotate(score=…).annotate(score3=F(β€˜score’)+3)
1 Like

Thanks. It is working now. Much appreciated