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

编码器

我是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')
威廉·范昂塞姆

您可以使用Postswith的数量注释模型对象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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用VBA宏按变量过滤

来自分类Dev

使用VBA宏按变量过滤

来自分类Dev

使用变量过滤 JSON 数据

来自分类Dev

Terraform:使用变量创建多个度量过滤器和警报

来自分类Dev

R:使用 string_select 和两个变量过滤 - 语法?

来自分类Dev

Ansible 变量过滤器和扩展

来自分类Dev

使用dplyr根据日期变量过滤行

来自分类Dev

使用变量过滤复制数据源

来自分类Dev

如何使用外部变量过滤地图列表

来自分类Dev

使用 JavaScript 根据两个变量过滤卡片

来自分类Dev

布尔变量过滤varchar

来自分类Dev

布尔变量过滤varchar

来自分类Dev

在HList上进行协变量过滤

来自分类Dev

nunjucks循环变量过滤器

来自分类Dev

AngularJS-通过变量过滤Json

来自分类Dev

AngularJS-通过变量过滤Json

来自分类Dev

根据字段=变量过滤行

来自分类Dev

SQLAlchemy 查询的变量过滤器

来自分类Dev

使用R data.table中的双变量过滤因子变量

来自分类Dev

在python中使用条件控制变量过滤数组以创建numpy矩阵

来自分类Dev

如何使用多列中的变量过滤sqlite表中的行数据?

来自分类Dev

如何使用数组变量过滤 ng-repeat 中的值?

来自分类Dev

R使用向量过滤数据帧

来自分类Dev

使用变量和IN进行过滤

来自分类Dev

流星:如何通过会话变量过滤数据

来自分类Dev

VBA多个条件/变量过滤器

来自分类Dev

PHP MySQL变量过滤器-“ AND”的行为类似于“ OR”

来自分类Dev

结合两个变量过滤器Django

来自分类Dev

VBA多个条件/变量过滤器