我已经编写了一个关于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
我们可以进行一个GROUP BY ... COUNT或者一个GROUP BY ... SUM在Django的ORM SQL的等效查询,使用的annotate(),values()的django.db.models的Count和Sum尊敬和可选的方法order_by()方法:
GROUP BY ... COUNT
GROUP BY ... SUM
annotate()
values()
django.db.models
Count
Sum
order_by()
from django.db.models import Count result = Books.objects.values('author') .order_by('author') .annotate(count=Count('author'))
现在结果包含具有两个键的字典:author和count:
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 ... | ...