Arundas R
Arundas R

Reputation: 770

Django group by to find the count

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

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

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

Related Questions