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

后端 未结 4 1112
迷失自我
迷失自我 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 17:59

    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'))
    

提交回复
热议问题