Home >Backend Development >Python Tutorial >How Do I Perform Group By Queries in Django?
When querying a Django model, you may encounter a scenario where you need to perform a group by operation. Attempting to use .group_by() as you would in SQL results in an error.
Instead of using .group_by(), Django provides aggregation methods that allow you to perform complex queries involving groupings. Specifically, Count is useful for counting the occurrences of a particular field.
To group the results by designation and count the occurrences, you would use the following code:
from django.db.models import Count result = (Members.objects .values('designation') .annotate(dcount=Count('designation')) .order_by() )
This query is similar to the following SQL statement:
SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation
The output of the Django query would be in the form:
[{'designation': 'Salesman', 'dcount': 2}, {'designation': 'Manager', 'dcount': 2}]
The above is the detailed content of How Do I Perform Group By Queries in Django?. For more information, please follow other related articles on the PHP Chinese website!