如何计算django中聚合的平均值

How to compute average of an aggregate in django

如果我有一个聚合,我可以得到查询中值的平均值,而不用在 python 内存中计算吗?

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

有什么方法可以获取查询中 subtotal 值的 Avg 吗?它给了我一个错误,我不允许在聚合(“subtotal”)上计算 Avg,但我无法替换 .values('id') 分组,因为 .annotate(...math here...) 内部操作不 distributiveModel 个对象。

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。注意:output_fieldSum的参数,不是annotate().