Home >Backend Development >Python Tutorial >How to Group Data Using Django's Querysets?
In Django, fetching data from the database often involves using querysets. These querysets provide various methods for filtering, ordering, and manipulating data. One common operation is grouping data by a specific field, similar to the SQL GROUP BY clause.
To group data in Django, one can utilize the aggregation features of the ORM. For instance, consider the following query that retrieves all members:
Members.objects.all()
This query returns a list of tuples, each tuple representing a member's details:
[('Eric', 'Salesman', 'X-Shop'), ('Freddie', 'Manager', 'X2-Shop'), ('Teddy', 'Salesman', 'X2-Shop'), ('Sean', 'Manager', 'X2-Shop')]
To group these results by the designation field, one can use the values() and annotate() methods:
from django.db.models import Count result = ( Members.objects .values('designation') .annotate(dcount=Count('designation')) .order_by() )
This query generates a SQL statement similar to:
SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation
The result is a list of dictionaries, each representing a designation and the count of members for that designation:
[{'designation': 'Salesman', 'dcount': 2}, {'designation': 'Manager', 'dcount': 2}]
To include multiple fields in the results, simply add them as arguments to the values() method, as shown here:
.values('designation', 'first_name', 'last_name')
For more information on aggregation and grouping in Django, refer to the following resources:
The above is the detailed content of How to Group Data Using Django's Querysets?. For more information, please follow other related articles on the PHP Chinese website!