How to execute a GROUP BY … COUNT or SUM in Django ORM?

后端 未结 1 1820
面向向阳花
面向向阳花 2020-11-27 18:00

Prologue:

This is a question arising often in SO:

  • Django Models Group By
  • Django equivalent for count and group by
  • Ho
相关标签:
1条回答
  • 2020-11-27 18:30

    We can perform a GROUP BY ... COUNT or a GROUP BY ... SUM SQL equivalent queries on Django ORM, with the use of annotate(), values(), the django.db.models's Count and Sum methods respectfully and optionally the order_by() method:

    • GROUP BY ... COUNT:

      from django.db.models import Count
      
      result = Books.objects.values('author')
                            .order_by('author')
                            .annotate(count=Count('author'))
      

      Now result contains a dictionary with two keys: author and 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'))
      

      Now result contains a dictionary with two columns: author and total_price:

        author    | total_price
      ------------|-------------
       OneAuthor  |    100.35
      OtherAuthor |     50.00
          ...     |      ...
      
    0 讨论(0)
提交回复
热议问题