Reputation: 770
I have models as given below.
class Page(models.Model):
name = models.CharField(max_length=150)
city = models.CharField(max_length=50)
country = models.ForeignKey(Country)
class Country(models.Model):
name = models.CharField(max_length=150)
All i need is to get the count of pages with each country. i.e,
{country1: 3, country2: 4}
(Country specific page count)
Is it possible to get the count of the pages based on the country foreign key as shown?
Upvotes: 2
Views: 363
Reputation: 276266
You can annotate with a count:
pages = Page.objects.annotate(num_countries=Count('country'))
pages[0].num_countries # 3
pages[1].num_countries # 4
There are plenty of details and examples about this in the aggregation API docs.
Upvotes: 2