我们经常会对orm 查询集做一些聚合操作,一般会想到集合遍历再累加,这通常的低效的,DJANGO ORM 有提供aggregate 方法我们在拉取查询机的时候可以更高效的生成一些聚合结果
from django.db.models import Sum
# 获取查询集
queryset = self.queryset.filter(id__in=(100, 200))
# 构建一个聚合结果
temp_aggr = queryset.aggregate(total_count=Sum('count'),
max_count=Max('count'))
# 获取聚合结果
total_count = temp_aggr['total_count'] or 0
max_count = temp_aggr['max_count'] or 0
# 其他聚合函数
'Avg', 'Count', 'Max', 'Min', 'Sum', 'Variance'
平均数, 计数,最大值,最小值,求和,方差