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

时间:2017-08-07 13:06:53

标签: python django group-by django-orm

序言

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

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

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

问题:

假设模型:

Info.plist

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

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

    GROUP BY ... COUNT
  • SELECT author, COUNT(author) AS count FROM myapp_books GROUP BY author

    GROUP BY ... SUM

1 个答案:

答案 0 :(得分:10)

我们可以使用annotate()values()SELECT author, SUM (price) AS total_price FROM myapp_books GROUP BY author 来对Django ORM执行GROUP BY ... COUNTGROUP BY ... SUM个SQL等效查询谨慎django.db.modelsCount方法以及order_by()方法可选:

  • GROUP BY ... COUNT:

    Sum

    现在结果包含一个字典,其中包含两个键:result = Books.objects.values('author') .order_by('author') .annotate(count=Count('author')) author

    count
  • GROUP BY ... SUM:

      author    | count
    ------------|-------
     OneAuthor  |   5
    OtherAuthor |   2
       ...      |  ...
    

    现在结果包含一个字典,其中有两列: result = Books.objects.values('author') .order_by('author') .annotate(total_price=Sum('price')) author

    total_price