如何在Django中计算聚合的平均值 [英] How to compute average of an aggregate in django

查看:266
本文介绍了如何在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(...在这里...)内的操作不是分布在模型中使用对象。

解决方案

从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()


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.

解决方案

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().

这篇关于如何在Django中计算聚合的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆