简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM