[Django]-Django: Better way to aggregate QuerySet results

6👍

You can annotate the values of the queryset with the number of items, like:

result = genders.values('answer').annotate(
    number=Count('answer')
).order_by('answer')

This will result in a QuerySet that looks like:

<QuerySet [
    { 'answer': 'Male', 'number': 14},
    { 'answer': 'Female', 'number': 25}
]>

1👍

# if your model name is QuestionFocus, then your query should be like this

QuestionFocus.objects.values('answer').annotate(number=Count('answer'))

Leave a comment