Home >Backend Development >Python Tutorial >How to Perform GROUP BY Queries in Django?
How to Achieve Group By Query in Django?
In Django, to perform a group by query on a model, one can employ the aggregation features of the ORM. This is achieved by utilizing the values() and annotate() methods.
Consider the following example:
from django.db.models import Count result = (Members.objects .values('designation') .annotate(dcount=Count('designation')) .order_by() )
This code translates to a SQL query similar to:
SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation
The result of the query will be a list of dictionary objects, each representing a group. For instance:
[{'designation': 'Salesman', 'dcount': 2}, {'designation': 'Manager', 'dcount': 2}]
To include multiple fields in the results, simply add them as arguments to values():
.values('designation', 'first_name', 'last_name')
References:
The above is the detailed content of How to Perform GROUP BY Queries in Django?. For more information, please follow other related articles on the PHP Chinese website!