一尘不染

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

django

我已经编写了一个关于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

阅读 1560

收藏
2020-03-31

共1个答案

一尘不染

我们可以进行一个GROUP BY ... COUNT或者一个GROUP BY ... SUM在Django的ORM SQL的等效查询,使用的annotate()values()django.db.modelsCountSum尊敬和可选的方法order_by()方法:

GROUP BY … COUNT:

from django.db.models import Count

result = Books.objects.values('author')
                      .order_by('author')
                      .annotate(count=Count('author'))

现在结果包含具有两个键的字典:authorcount

  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
    ...     |      ...
2020-03-31