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:

  • How to query as GROUP BY in django?
  • Django equivalent of COUNT with GROUP BY

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)