我试图在我的索引页面中显示评论数量,就像我在帖子页面中显示它一样。但是,我的def指数没有slug参数。
对于我的post.html我可以显示这样的评论数量
/process=Separate
并在模板中
#for single-post page
def post(request, slug):
post = get_object_or_404(Post, slug=slug)
comments_count = Comment.objects.filter(post=post).count()
context_dict = {
'comments_count':comments_count,
}
return render(request, 'main/post.html', context_dict)
我想为我的索引页面做同样的事情。
{{comments_count}}
答案 0 :(得分:1)
最简单的方法是添加一种方法来为Post
模型计算评论:
class Post(models.Model):
...
def comments_count(self):
return Comment.objects.filter(post=self).count()
然后在您的模板中使用它,例如:
{% for post in posts %}
{{ post.title }}: {{ post.comments_count }}
{% endfor %}