How to uses group by to query data in Django orm

created at 07-15-2021 views: 2

if you want to use orm in django to implement the following sql statement functions:

SELECT ptype, COUNT(ptype) AS dcount
FROM people GROUP BY ptype

Use django's ORM aggregation function

from django.db.models import Count
People.objects.values('ptype').annotate(dcount=Count('ptype'))

The above query is equivalent to the SQL statement:

SELECT ptype, COUNT(ptype) AS dcount
FROM people GROUP BY ptype

The result returned is:

[{'ptype': 'studen', 'dcount': 10}, 
 {'ptype': 'teacher', 'dcount': 2}]
Please log in to leave a comment.