113👍
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:
23👍
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'))
- [Django]-Django auto_now and auto_now_add
- [Django]-Sorting related items in a Django template
- [Django]-Django import error – No module named core.management
7👍
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)
- [Django]-Whats the difference between using {{STATIC_URL}} and {% static %}
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-How to set True as default value for BooleanField on Django?
4👍
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')
- [Django]-Why is __init__ module in django project loaded twice
- [Django]-Django – filtering on foreign key properties
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
Source:stackexchange.com