序言:
这是 SO 上经常出现的问题:
- Django Models Group By
- Django equivalent for count and group by
- How to query as GROUP BY in django?
- How to use the ORM for the equivalent of a SQL count, group and join query?
我在 SO 文档中编写了一个示例,但由于文档将于2017年8月8日关闭,我将遵循这个广受赞同和讨论的元答案的建议,并将我的示例转换为自我回答的帖子。
当然,我也非常乐意看到任何不同的方法!!
问题:
假设有以下模型:
class Books(models.Model):
title = models.CharField()
author = models.CharField()
price = models.FloatField()
我如何利用Django ORM在该模型上执行以下查询:
GROUP BY ... COUNT
:SELECT author, COUNT(author) AS count FROM myapp_books GROUP BY author
GROUP BY ... SUM
:SELECT author, SUM (price) AS total_price FROM myapp_books GROUP BY author
order_by(...)
部分。如果模型使用不同的列进行排序,则省略order_by()
子句将导致聚合失败。 - dgw