版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33867131/article/details/82706698
1、所有聚合函数都放在 django.db.models 下面:
2、聚合函数不能单独执行,需要放在aggregate/annotate下面去执行:
result = Book.objects.aggregate(Avg("price"))
3、聚合函数执行完后,会给结果默认取个名字(filed+__+聚合函数名字,上述代码结果名字:price__avg)
可以用下述方法,自定义返回结果名字:result = Book.objects.aggregate(avg = Avg("price"))
聚合函数执行完成的结果名字,变为了avg
4、
aggregate方法:返回值是一个字典(key:就是名字,值:就是执行结果)
annotate方法:返回是一个QuerySet对象(除下述场景之外都使用aggregate方法)
使用annotate场景:(需要查询出每本书的平均销售价格,总销售额,等等)
Book表:
name pages price author
三国 3000 30 罗贯中
红楼 5000 30 曹雪芹
水浒 3000 30 施耐庵
Bookorder表:
name price
三国 25
三国 30
三国 35
红楼 50
红楼 60
水浒 20
在每条图书数据上都添加一个字段叫做avg,计算这本书的平均销售价格
from djang.db.models import Avg
result = Book.objects.annotate(avg=Avg("bookorder__price"))
调用之后返回结果,相当于:
name pages price author avg
三国 3000 30 罗贯中 (25+30+35)/3
红楼 5000 30 曹雪芹 (50+60)/2
水浒 3000 30 施耐庵 (20)/1
(1) Avg:求平均值
获取所有图书的价格平均值
from django.db.models import Avg
result = Book.objects.aggregate(Avg('price'))
print(result)
以上的打印结果是:{"price__avg":23.0}
(2)Count:统计指定字段的个数
获取Book表中一总有多少本图书
from django.db.models import Count
result = Book.objects.aggregate(total=Count('id'))
获取作者表中所有的不重复的邮箱总共有多少个
from djang.db.models import Count
result = Author.objects.aggregate(count=Count('email',distinct=True))
(3) Max和Min:获取指定字段的最大值和最小值
获取Author表中,最大的年龄和最小的年龄分别是多少
from django.db.models import Max,Min
result = Author.objects.aggregate(Max('age'), Min('age'))
返回结果:{"age__max":88,"age__min":18}
(4)Sum:求指定字段的总和
求图书的销售总额
from djang.db.models import Sum
result = BookOrder.objects.aggregate(total=Sum("price"))