shubham
shubham

Reputation: 55

How to get count in Django for a model two foreign keys away

I have three modles in my Django app as follows:

class City(models.Model):
    city_name = models.CharField(length=50)

class Area(models.Model):
    city = models.ForeignKey(City)
    area_name = models.CharField(length=50)

class Person(models.Model):
    area = models.ForeignKey(Area)
    person_name = models.CharField(length=50)

I require cities in order of their population (i.e. Person basis). How is it possible with Django?

Upvotes: 0

Views: 235

Answers (1)

Reza Heydari
Reza Heydari

Reputation: 1211

Use annotate to count population.

City.objects.annotate(population=Count("area_set___person_set")).order_by("population")

Upvotes: 2

Related Questions