使用变量过滤和计数 QuerySet 项目

我是 Django 新手,正在开发一个非常基本的社交媒体网站作为练习项目。


现在,我正在尝试弄清楚如何根据变量过滤查询集并计算查询集中有多少项与过滤器匹配。


为了演示我想要做什么,假设我正在循环浏览所有可见的帖子(例如 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')


潇湘沐
浏览 130回答 1
1回答

慕少森

您可以Posts使用以下数量注释模型对象Comments:def index(request):&nbsp; &nbsp; all_posts = Posts.objects.annotate(&nbsp; &nbsp; &nbsp; &nbsp; ncomments=Count('comments')&nbsp; &nbsp; ).order_by('-date_published')&nbsp; &nbsp; all_comments = Comments.objects.order_by('-date_published')&nbsp; &nbsp; context = {&nbsp; &nbsp; &nbsp; &nbsp; 'all_posts': all_posts,&nbsp; &nbsp; &nbsp; &nbsp; 'all_comments': all_comments&nbsp; &nbsp; }&nbsp; &nbsp; return render(request, 'social/index.html', context)在模板中,您可以使用以下命令进行渲染:{% post in all_posts %}&nbsp; &nbsp; <h1> There are currently {{ post.ncomments }} comments on this post</h1>{% endfor %}注意:通常 Django 模型有一个单一的名称,所以Post而不是Posts.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python