django most efficient way to count same field values in a query

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:

Leave a Comment