Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .extra() on fields created by .annotate() in Django

I want to retrieve a sum of two fields (which are aggregations themselves) for each object in a table.

The following may describe a bit better what I'm after but results in an Unknown column in field list-Error:

items = MyModel.objects.annotate(
                field1=Sum("relatedModel__someField"),
                field2=Sum("relatedModel__someField")).extra(
                        select={"sum_field1_field2": "field1 + field2"})

I also tried using F() for the field lookups but that gives me an invalid sql statement.

Any ideas on how to solve this are much appreciated.

like image 912
jnns Avatar asked Feb 04 '11 14:02

jnns


People also ask

What is the use of annotate in Django?

Django annotations 2 are a way of enriching the objects returned in QuerySets. That is, when you run queries against your models you can ask for new fields, whose values will be dynamically computed, to be added when evaluating the query. These fields will be accessible as if they were normal attributes of a model.

What is difference between annotate and aggregate Django?

Unlike aggregate() , annotate() is not a terminal clause. The output of the annotate() clause is a QuerySet ; this QuerySet can be modified using any other QuerySet operation, including filter() , order_by() , or even additional calls to annotate() .

What is QuerySet annotate?

In simpler terms, annotate allows us to add a pseudo field to our queryset. This field can then further be used for filter lookups or ordering.\ Ex: Suppose you want to all the Books along with the total number of chapters present in each one, then you could use annotate as follows: Simple annotate example.


1 Answers

it this what you want?

items = MyModel.objects.extra(
    select = {'sum_field1_field2': 'SUM(relatedModel__someField) + SUM(relatedModel__someField)'},
)
like image 100
yedpodtrzitko Avatar answered Sep 17 '22 12:09

yedpodtrzitko