Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute average of an aggregate in django

If I have an aggregate, can I get the average of the values in the query, without computing it in python memory?

from django.db.models import F, Sum, FloatField, Avg
Model.objects.filter(...)\
    .values('id')\
    .annotate(subtotal=Sum(...math here...), output_field=FloatField())\
    .annotate(total=Avg(F('subtotal'))) #this line throws a FieldError

Is there any way to get the Avg of the subtotal values in the query? It gives me an error that I'm not allowed to compute Avg on an aggregate ("subtotal"), but I can't replace the .values('id') grouping because the .annotate(...math here...) operations inside aren't distributive accross Model objects.

like image 701
Escher Avatar asked Jun 24 '16 20:06

Escher


People also ask

How does Django calculate average?

You simply using values() , aggregate() and function Avg() and F() .

What does aggregate do in Django?

When specifying the field to be aggregated in an aggregate function, Django will allow you to use the same double underscore notation that is used when referring to related fields in filters. Django will then handle any table joins that are required to retrieve and aggregate the related value.

What is F in Django ORM?

In the Django QuerySet API, F() expressions are used to refer to model field values directly in the database.


1 Answers

from django.db.models import F, Sum, FloatField, Avg
Model.objects.filter(...)\
    .values('id')\
    .annotate(subtotal=Sum(...math here..., output_field=FloatField()))\
    .aggregate(total=Avg(F('subtotal')))

Aggregating annotations. Note: output_field is parameter of Sum, not annotate().

like image 170
Vladimir Danilov Avatar answered Oct 04 '22 21:10

Vladimir Danilov