简体   繁体   English

如何使用注释汇总所有行并获得平均值? 詹戈

[英]how to use annotate to sum up all rows and get the avg? django

I was googling about this and there is a simplier way which uses Cast but then thing is I believe that's for django 2.0 that mine is django 1.9 我正在谷歌上搜索,并且有一种使用Cast的简单方法,但是我相信那是针对django 2.0 ,我的是django 1.9

I found a post and I tried it, it doesn't really work for me though. 我找到了一个帖子,并尝试了它,但是它实际上对我不起作用。

Let's say I have a model with value and max fields. 假设我有一个包含valuemax字段的模型。 I want to get the sum of all value and max then divide them to get the average. 我想获得所有valuemax的总和,然后将它们除以得出平均值。 What I did just gets one row and return the avg of the row, can someone let me know what I have been doing wrong here? 我所做的只是获得一行并返回该行的平均值,有人可以让我知道我在这里做错了什么吗?

model_calcuation = Model.objects.filter().annotate(
    sum_score=Sum('value', output_field=FloatField()),
    sum_max=Sum('max', output_field=FloatField())
).annotate(
    avg=F('sum_score') / F('sum_max')
)

Thanks in advance for any help 预先感谢您的任何帮助

If I understood correctly your question, you are looking for aggregate() operation. 如果我正确理解了您的问题,那么您正在寻找aggregate()操作。

from django.db.models import F, Sum

model_calcuation = Model.objects.aggregate(result=Sum(F('value')) / Sum(F('max')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM