Prologue:
This is a question arising often in SO:
- Django Models Group By
- Django equivalent for count and group by
- How to query as GROUP BY in django?
- How to use the ORM for the equivalent of a SQL count, group and join query?
I have composed an example on SO Documentation but since the Documentation will get shut down on August 8, 2017, I will follow the suggestion of this widely upvoted and discussed meta answer and transform my example to a self-answered post.
Of course, I would be more than happy to see any different approach as well!!
Question:
Assume the model:
class Books(models.Model):
    title  = models.CharField()
    author = models.CharField()
    price = models.FloatField()
How can I perform the following queries on that model utilizing 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
 
     
    