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

后端 未结 4 1118
迷失自我
迷失自我 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条回答
  •  不知归路
    2020-12-04 18:09

    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)
    

提交回复
热议问题