Šarūnas Rakauskas
Šarūnas Rakauskas

Reputation: 168

Django counting one to many relationship

So i have two tables, Post and Category

Code:

model.py

class Category(models.Model):
     category = models.CharField(max_length=100)

     def __str__(self):
         return self.category

class Post(models.Model):
     title = models.CharField(max_length=200)
     author = models.CharField(max_length=40)
     category = models.ForeignKey(Category)
     content = models.TextField()
     created_date = models.DateTimeField(default=timezone.now)

     class Meta:
         ordering = ['-created_date']

     def __str__(self):
         return self.title + ' - ' + str(self.created_date.date())

And I want to implement category list in template. For example I have few categories

Sports(2) 2-number of how many posts are within sports category

template code:

<h3>Categories</h3>
    <ul class="nav navbar-stacked">
        {% for category in categories %}
            <li><a href="#">{{ category }}<span class="pull-right">(
                {{ **post.category.count** }}
            )</span></a></li>
        {% endfor %}
    </ul>

How can I achieve this?

Upvotes: 5

Views: 4088

Answers (1)

narendra-choudhary
narendra-choudhary

Reputation: 4818

In template, you can do

{{ category.post_set.count }}

to get count of Post objects with category mapped to given category object.

You can read more about reverse lookups here.

Upvotes: 6

Related Questions