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

Prologue:

This often raises the question in SO:

I made an example on SO Documentation, but since the Documentation will be closed on August 8, 2017, I will follow up on the proposal for this widely accepted and discussed meta-answer and convert my example into a standalone answer.

Of course, I would be more than happy to see any other approach.


Question:

Suppose the model:

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

How can I execute the following queries for this model using 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
    
+4
1

SQL- GROUP BY... COUNT GROUP BY... SUM Django ORM annotate(), values(), django.db.models Count Sum order_by():

  • GROUP BY... COUNT:

    from django.db.models import Count
    
    result = 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
        ...     |      ...
    
+12

Source: https://habr.com/ru/post/1736751/


All Articles