【问题标题】:Django counting one to many relationshipDjango计算一对多关系
【发布时间】:2017-07-16 17:46:01
【问题描述】:

所以我有两个表,PostCategory

代码:

模型.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())

我想在模板中实现类别列表。例如我的类别很少

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

模板代码:

<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>

我怎样才能做到这一点?

【问题讨论】:

    标签: python django python-2.7 django-models django-templates


    【解决方案1】:

    在模板中,你可以这样做

    {{ category.post_set.count }}
    

    获取Post 对象的计数,其中category 映射到给定的类别对象。

    您可以阅读有关反向查找的更多信息here

    【讨论】:

    • 还有4分钟,好像15分钟不过去我接受不了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-11
    • 2015-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2015-07-05
    相关资源
    最近更新 更多