聚合
常用的聚合函數(shù) Avg, Max, Min
實(shí)例1
# 計(jì)算所有圖書的平均價(jià)格
>>> Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}
實(shí)例2
>>> from django.db.models import Avg, Max, Min
>>> Book.objects.aggregate(Avg('price'), Max('price'), Min('price'))
{'price__avg': 34.35, 'price__max': Decimal('81.20'), 'price__min': Decimal('12.99')}
分組
emp表模型
class Emp(models.Model):
name=models.CharField(max_length=32)
age=models.IntegerField()
salary=models.DecimalField(max_digits=8,decimal_places=2)
dep=models.CharField(max_length=32)
province=models.CharField(max_length=32)
- 總結(jié) :跨表分組查詢本質(zhì)就是將關(guān)聯(lián)表join成一張表,再按單表的思路進(jìn)行分組查詢。
(1) 練習(xí):統(tǒng)計(jì)每一個(gè)出版社的最便宜的書
publishList=Publish.objects.annotate(MinPrice=Min("book__price"))
for publish_obj in publishList:
print(publish_obj.name,publish_obj.MinPrice)
annotate的返回值是querySet,如果不想遍歷對(duì)象,可以用上valuelist:
queryResult= Publish.objects
.annotate(MinPrice=Min("book__price"))
.values_list("name","MinPrice")
print(queryResult)
(2) 練習(xí):統(tǒng)計(jì)每一本書的作者個(gè)數(shù)
ret=Book.objects.annotate(authorsNum=Count('authors__name'))
(3) 統(tǒng)計(jì)每一本以py開頭的書籍的作者個(gè)數(shù):
queryResult=Book.objects
.filter(title__startswith="Py")
.annotate(num_authors=Count('authors'))
(4) 統(tǒng)計(jì)不止一個(gè)作者的圖書:
queryResult=Book.objects
.annotate(num_authors=Count('authors'))
.filter(num_authors__gt=1)
(5) 根據(jù)一本圖書作者數(shù)量的多少對(duì)查詢集 QuerySet進(jìn)行排序:
Book.objects.annotate(num_authors=Count('authors')).order_by('num_authors')
(6) 查詢各個(gè)作者出的書的總價(jià)格:
# 按author表的所有字段 group by
queryResult=Author.objects
.annotate(SumPrice=Sum("book__price"))
.values_list("name","SumPrice")
print(queryResult)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。