我是 Django 新手,正在開發一個非?;镜纳缃幻襟w網站作為練習項目?,F在,我正在嘗試弄清楚如何根據變量過濾查詢集并計算查詢集中有多少項與過濾器匹配。為了演示我想要做什么,假設我正在循環瀏覽所有可見的帖子(例如 Facebook 帖子或類似的帖子),并且我想要顯示每個帖子的評論數量。這就是我的做法:{% post in all_posts %} <h1> There are currently {{ HOW DO I FILTER AND COUNT? }} comments on this post</h1>{% endfor %}這是我的文件的相關部分的樣子views.py:def index(request): all_posts = Posts.objects.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)評論通過 postID 變量鏈接到帖子。所以,我知道這不起作用,但理想情況下我想HOW DO I FILTER AND COUNT?用以下內容替換我的模板部分:{{ all_comments.filter(postID=post).count }}有沒有一種簡單的方法可以在我的views.py或模板本身中執行此操作?我遇到的主要問題是我不知道如何將post模板中的變量傳遞給某個返回我正在查找的計數的函數。更新:以下是我的帖子和評論模型:class Posts(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=200) content = models.TextField() date_published = models.DateTimeField('date posted') class Comments(models.Model): postID = models.ForeignKey(Posts, on_delete=models.CASCADE) commenter = models.CharField(max_length=200) email = models.EmailField(max_length=200) content = models.TextField() date_published = models.DateTimeField('date posted')
1 回答

慕少森
TA貢獻2019條經驗 獲得超9個贊
您可以Posts使用以下數量注釋模型對象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)
在模板中,您可以使用以下命令進行渲染:
{% post in all_posts %}
<h1> There are currently {{ post.ncomments }} comments on this post</h1>
{% endfor %}
注意:通常 Django 模型有一個單一的名稱,所以Post而不是Posts.
添加回答
舉報
0/150
提交
取消