如何在Django中计算聚合的平均值 [英] How to compute average of an aggregate in django
问题描述
如果有聚合,是否可以在查询中获得平均值,而无需在python内存中进行计算?
从django.db.models导入F,Sum,FloatField,平均
Model.objects.filter(...)\
.values('id')\
。 annotate(subtotal = Sum(... math here ...),output_field = FloatField())\
.annotate(total = Avg(F('subtotal')))#此行引发FieldError
有什么方法可以得到 Avg
的查询中的小计
值?它给我一个错误,不允许我对总计( 小计
)进行平均
的计算,但是我无法替换 .values('id')
分组,因为 .annotate(...在这里...)
内的操作不是分布在模型中使用
对象。
汇总注释一个>。注意: If I have an aggregate, can I get the average of the values in the query, without computing it in python memory? Is there any way to get the Aggregating annotations. Note: 这篇关于如何在Django中计算聚合的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!从django.db.models导入F,总和,FloatField,Avg
Model.objects.filter(...)\
.values('id')\
.annotate(subtotal = Sum(...在这里..,output_field = FloatField()))
.aggregate(total = Avg(F('subtotal')))
output_field
是 Sum
的参数,而不是 annotate()
。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
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.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')))
output_field
is parameter of Sum
, not annotate()
.