django中ORM使用聚合函数方法

两个方法:

1、aggregate直接返回聚合函数的值,如sum,avg等 

problems=Problem.objects.filter(user=user).aggregate(Sum('reply_not_read'))

2、annotate,将聚合函数的值加入返回的QuerySet 中

Document.objects.annotate(popularity=Count('comments'))
现在,这个中间 QuerySet 包含了与每个文件相关联的所有注释的计数值,我们就可以按这个字段进行排序了。由于我们希望把拥有最多注释的文档显示排在第一个,所以我们采用了降序,比如.order_by('-comments__count') 。
原文地址:https://www.cnblogs.com/lddhbu/p/2599941.html