Django-ORM-查询API-聚合查询和分组查询

有Book (id, title, price,date, publish)、Publish (id, name, addr)、Author (id, name)三张表:

Book表和Publish表是一对多的关系,Book与Author表是多对多的关系。

模块引用:from django.db.models import Avg,Sum,Max,Min

查询所有书籍的平均价格:Book.objects.all().aggregate(Avg('price'))    ———— {'price__avg': 302.571429}

查询每个作者出版过的书的最高价格:Book.objects.values('authors__name').annotate(Max('price'))

<QuerySet [{'authors__name': '加西亚-马尔克斯', 'price__max': Decimal('99.00')}, {'authors__name': '皎皎', 'price__max': Decimal('89.00')}, {'authors__name': '
peterpan', 'price__max': Decimal('666.00')}, {'authors__name': '陈冠希', 'price__max': Decimal('998.00')}, {'authors__name': '兰陵笑笑生', 'price__max': Decima
l('128.00')}, {'authors__name': 'George-Martin', 'price__max': Decimal('89.00')}]>

Life is short,i use python!
原文地址:https://www.cnblogs.com/chengnanlangzi/p/7464794.html