django queryset group by count

+1 vote
asked Mar 14 by katib (112 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


[{'role': '1', 'rcount': 9}, 
 {'role': '2', 'rcount': 11}]
Welcome , qPocho is an online community for programmers share there knowledge.