我是Django的新手,并且正在一个非常基本的社交媒体网站上作为练习项目。
现在,我试图找出如何基于变量过滤QuerySet并计算QuerySet中有多少项目与过滤器匹配。
为了演示我正在尝试做的事情,假设我正在浏览所有可见的帖子(例如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')
您可以使用Posts
with的数量注释模型对象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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句