Reputation: 23
I've searched high and low trying to figure this out, but have come up empty.
I have the following model:
class Person(models.Model):
street_name = models.CharField(max_length=64)
My goal is to get the unique set of street_name's annotated with the number of people on the street, ideally in the final form of [('Street 1', 45), ('Street 2', 26), ...]
Currently I do this as follows:
unique_streets = Person.objects.values_list('street_name', flat=True).distinct()
street_counts = []
for street in unique_streets:
street_counts.append(Person.objects.filter(street_name=street).count())
people_on_street = zip(unique_streets, street_counts)
This is inefficient because each iteration of the for loop incurs an extra database hit. Is it possible to do this in one or two queries?
Upvotes: 1
Views: 51
Reputation: 599490
Yes, with aggregation.
from django.db.models import Count
street_counts = Person.objects.values('street_name').annotate(Count('street_name'))
Upvotes: 2