如何在Django ORM中执行GROUP BY ... COUNT或SUM?

问题描述 投票:4回答:1

序幕:

这是SO中经常出现的问题:

我已经在SO文档中编写了一个示例,但由于文档将于2017年8月8日关闭,我将遵循this widely upvoted and discussed meta answer的建议并将我的示例转换为自我回答的帖子。

当然,我也很乐意看到任何不同的方法!


题:

假设模型:

class Books(models.Model):
    title  = models.CharField()
    author = models.CharField()
    price = models.FloatField()

如何使用Django ORM在该模型上执行以下查询:

  • GROUP BY ... COUNTSELECT author, COUNT(author) AS count FROM myapp_books GROUP BY author
  • GROUP BY ... SUMSELECT author, SUM (price) AS total_price FROM myapp_books GROUP BY author
python django group-by django-orm
1个回答
10
投票

我们可以在Django ORM上执行GROUP BY ... COUNTGROUP BY ... SUM SQL等效查询,使用annotate()values()django.db.modelsCountSum方法,并且可选地使用order_by()方法:

  • GROUP BY ... COUNT: result = Books.objects.values('author') .order_by('author') .annotate(count=Count('author')) 现在结果包含一个包含两个键的字典:authorcount author | count ------------|------- OneAuthor | 5 OtherAuthor | 2 ... | ...
  • GROUP BY ... SUM: result = Books.objects.values('author') .order_by('author') .annotate(total_price=Sum('price')) 现在结果包含一个包含两列的字典:authortotal_price author | total_price ------------|------------- OneAuthor | 100.35 OtherAuthor | 50.00 ... | ...
© www.soinside.com 2019 - 2024. All rights reserved.