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

后端 未结 4 1102
迷失自我
迷失自我 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'))
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-12-04 18:03

    Unless your field value is always guaranteed to be in a specific case, it may be useful to transform it prior to performing a count, i.e. so 'apple' and 'Apple' would be treated as the same.

    from django.db.models import Count
    from django.db.models.functions import Lower
    
    MyModel.objects.annotate(lower_title=Lower('title')).values('lower_title').annotate(num=Count('lower_title')).order_by('num')
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题