如何在Django ORM中执行GROUP BY…COUNT或SUM?
我已经编写了一个关于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 countFROM myapp_books GROUP BY author
GROUP BY … SUM:
SELECT author, SUM (price) AS total_priceFROM myapp_books GROUP BY author
回答:
我们可以进行一个GROUP BY ... COUNT
或者一个GROUP BY ... SUM
在Django的ORM SQL的等效查询,使用的annotate()
,values()
的django.db.models
的Count
和Sum
尊敬和可选的方法order_by()
方法:
GROUP BY … COUNT:
from django.db.models import Countresult = Books.objects.values('author')
.order_by('author')
.annotate(count=Count('author'))
现在结果包含具有两个键的字典:author
和count
:
author | count------------|-------
OneAuthor | 5
OtherAuthor | 2
... | ...
|
GROUP BY … SUM:
from django.db.models import Sum result = Books.objects.values('author')
.order_by('author')
.annotate(total_price=Sum('price'))
现在结果包含一个包含两列的字典:author和total_price:
author | total_price------------|-------------
OneAuthor | 100.35
OtherAuthor | 50.00
... | ...
以上是 如何在Django ORM中执行GROUP BY…COUNT或SUM? 的全部内容, 来源链接: utcz.com/qa/434914.html