[Django]-Django most efficient way to count same field values in a query

113👍

You want something similar to “count … group by”. You can do this with the aggregation features of django’s ORM:

from django.db.models import Count

fieldname = 'myCharField'
MyModel.objects.values(fieldname)
    .order_by(fieldname)
    .annotate(the_count=Count(fieldname))

Previous questions on this subject:

23👍

This is called aggregation, and Django supports it directly.

You can get your exact output by filtering the values you want to count, getting the list of values, and counting them, all in one set of database calls:

from django.db.models import Count
MyModel.objects.filter(myfield__in=('abc', 'xyz')).\
        values('myfield').annotate(Count('myfield'))

7👍

You can use Django’s Count aggregation on a queryset to accomplish this. Something like this:

from django.db.models import Count
queryset = MyModel.objects.all().annotate(count = Count('my_charfield'))
for each in queryset:
    print "%s: %s" % (each.my_charfield, each.count)

4👍

Unless your field value is always guaranteed to be in a specific case, it may be useful to transform it prior to performing a count, i.e. so ‘apple’ and ‘Apple’ would be treated as the same.

from django.db.models import Count
from django.db.models.functions import Lower

MyModel.objects.annotate(lower_title=Lower('title')).values('lower_title').annotate(num=Count('lower_title')).order_by('num')
👤alstr

Leave a comment