user3329941
user3329941

Reputation: 23

Django, efficiently retrieve the count of multiple field filters

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

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

Yes, with aggregation.

from django.db.models import Count
street_counts = Person.objects.values('street_name').annotate(Count('street_name'))

Upvotes: 2

Related Questions