1 回答

TA貢獻(xiàn)2019條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以Posts使用以下數(shù)量注釋模型對(duì)象Comments:
def index(request):
all_posts = Posts.objects.annotate(
ncomments=Count('comments')
).order_by('-date_published')
all_comments = Comments.objects.order_by('-date_published')
context = {
'all_posts': all_posts,
'all_comments': all_comments
}
return render(request, 'social/index.html', context)
在模板中,您可以使用以下命令進(jìn)行渲染:
{% post in all_posts %}
<h1> There are currently {{ post.ncomments }} comments on this post</h1>
{% endfor %}
注意:通常 Django 模型有一個(gè)單一的名稱,所以Post而不是Posts.
添加回答
舉報(bào)