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

后端 未结 4 1114
迷失自我
迷失自我 2020-12-04 17:51

Lets say if I have a model that has lots of fields, but I only care about a charfield. Lets say that charfield can be anything so I don\'t know the possible values, but I kn

4条回答
  •  猫巷女王i
    2020-12-04 18:01

    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

提交回复
热议问题