Django基础aggregate和annotate方法使用详解

2021-12-30  本文已影响0人  吕保鑫

aggregate()方法详解
aggregate的中文意思是聚合, 源于SQL的聚合函数。Django的aggregate()方法作用是对一组值(比如queryset的某个字段)进行统计计算,并以字典(Dict)格式返回统计计算结果。django的aggregate方法支持的聚合操作有AVG / COUNT / MAX / MIN /SUM 等。

from django.shortcuts import render
from django.db.models import *
from myproject.models import *

# Create your views here.

Student.objects.aggregate(Max('score'))
#取最大分数值
#{'score__max': 99}
Student.objects.aggregate(min=Min('score'))
#取最小分数值
#{'min': 66}
Student.objects.aggregate(sum=Sum('score'))
#取总分数值
#{'sum': 253}
Student.objects.aggregate(avg=Avg('score'))
#取平均分数值
#{'avg': 84.3333}

annotate()方法详解
annotate的中文意思是注释,我觉得是非常地词不达意,一个更好的理解是分组(Group By)。如果你想要对数据集先进行分组然后再进行某些聚合操作或排序时,需要使用annotate方法来实现。与aggregate方法不同的是,annotate方法返回结果的不仅仅是含有统计结果的一个字典,而是包含有新增统计字段的查询集(queryset)。

Student.objects.values('cls').annotate(clsavg = Avg('score'))
#取每个班级的平均分数值
#QuerySet [{'cls': 1, 'clsavg': 93.5}, {'cls': 2, 'clsavg': 66.0}]>
Student.objects.values('cls').annotate(s = Sum('score')).aggregate(m = Max('s'))
#先取每个班级的总数值再取最大的值
#{'m': 187}
上一篇下一篇

猜你喜欢

热点阅读