You can use annotate()with values(). This approach is shown in the docs for values(). To get a counter for each category, you can do:
from django.db.models import Count
categories = Result.objects.filter(
event=myevent,
).order_by('category').values(
'category__name'
).annotate(count=Count('category__name'))
This will return a list of dictionaries with keys category__nameand count, for example:
[{'count': 3, 'category__name': u'category1'}, {'count': 1, 'category__name': u'category2'}]
You can convert this into a single dictionary using a dictionary understanding:
counts_by_category = {d['category__name']: d['count'] for f in categories}
source
share