django queryset group by count

+1 vote
54 views
asked Mar 14 by katib (115 points)

I want to perform group by and count via django ORM.

I have a model named Members

Normal sql looks like this

SELECT role, COUNT(role) AS rcount
FROM members GROUP BY role

1 Answer

0 votes
answered Mar 14 by anonymous

you can use annotate with sum to group by and count

from django.db.models import Count
Members.objects.values('role').annotate(dcount=Count('role'))

output

[{'role': '1', 'rcount': 9}, 
 {'role': '2', 'rcount': 11}]
...