[Fixed]-Using .extra() on fields created by .annotate() in Django

6👍

it this what you want?

items = MyModel.objects.extra(
    select = {'sum_field1_field2': 'SUM(relatedModel__someField) + SUM(relatedModel__someField)'},
)

0👍

To make it work for many to many or for many to one (reverse) relations, you may use the following:

items = MyModel.objects.extra(
    select = {'sum_field1_field2': 'SUM("relatedModel"."someField") + SUM("relatedModel"."someField")'},
      )

But this will break also if you need another annotate, like for a count, because extra will add the statement to the GROUP BY clause, whereas aggregate functions are not allowed in there.

👤Rmatt

Leave a comment