How to compute average of an aggregate in django

2019-05-21 18:17发布

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.

1条回答
萌系小妹纸
2楼-- · 2019-05-21 18:25
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().

查看更多
登录 后发表回答