Django模板中的Count方法无法按预期工作

断音

我正在构建一个新闻应用程序,该程序允许成员发表对文章的评论。我想在模板中显示文章,也要显示每篇文章已发表的评论数。我尝试使用count方法,但是它检索了我的评论表中的评论总数,而不是特定文章的评论总数。

#models.py
class Article(models.Model):
    #auto-generate indices for our options
    ENTRY_STATUS = enumerate(('no', 'yes'))
    #this will be a foreign key once account app is built
    author = models.CharField(default=1, max_length=1)
    category = models.ForeignKey(Category)
    title = models.CharField(max_length=50)
    entry = models.TextField()
    dateposted = models.DateTimeField(default=timezone.now, auto_now_add=True)
    draft = models.IntegerField(choices=ENTRY_STATUS, default=0)
    lastupdated = models.DateTimeField(default=timezone.now, auto_now=True)

    #prevents the generic labeling of our class as 'Classname object'
    def __unicode__(self):
        return self.title


class Comment(models.Model):
    #this will be a foreign key once account app is built
    author = models.CharField(default=1, max_length=1)
    article = models.ForeignKey(Article)
    dateposted = models.DateTimeField(auto_now_add=True)
    comment = models.TextField()

    def __unicode__(self):
        #returns the dateposted as a unicode string
        return unicode(self.dateposted)

#templates/list_articles.html
{% for comment in comments %}
    {% if comment.article_id == article.id %}
        {% if comments.count < 2 %}
            #this is returning all comments in comment table
            <b>{{ comments.count }} comment</b>
        {% else %}
            <b>{{ comments.count }} comments</b>
        {% endif %}
    {% endif %}
{% endfor %}

到目前为止,我所看到的所有示例都手动提供了一个值来过滤(例如Comment.objects.filter(article_id=x).count()),以我为例,我只能通过模板进行访问。

#views.py
class ArticlesListView(ListView):
    context_object_name = 'articles'
    # only display published pieces (limit 5)
    queryset = Article.objects.select_related().order_by('-dateposted').filter(draft=0)[:5]
    template_name = 'news/list_articles.html'

    # overide this to pass additional context to templates
    def get_context_data(self, **kwargs):
        context = super(ArticlesListView, self).get_context_data(**kwargs)
        #get all comments
        context['comments'] = Comment.objects.order_by('-dateposted')
        #get all article photos
        context['photos'] = Photo.objects.all()
        #context['total_comments'] = Comment.objects.filter(article_id=Article)
        return context

我的预期结果是列出所有文章,并在每篇文章下方汇总对该文章的评论(例如,第1条:4条评论,第5条:1条评论等)。 :第1条:4条评论,第5条:4条评论(即使第5条只有1条评论)

任何帮助表示赞赏。我已经花了5个小时来阅读文档,但是每个示例都手动提供了一个可供过滤的值。

丹尼尔·罗斯曼

我不确定为什么您会发现此意外。comments所有评论,所以当然comments.count是所有评论的总数。怎么会这样呢?您不会在任何地方过滤它们。

但是,这是做事的一种非常非常可怕的方式。绝对没有理由将所有注释传递给模板,然后遍历它们以检查它们是否是正确的文章。您从注释到文章都有一个外键,因此您应该使用相反的关系来获取相关的注释。

完全从您的视图中删除“注释”查询,然后在模板中执行此操作(替换整个嵌套的fors和ifs块):

{{ article.comment_set.count }}

但是,每篇文章只进行一次查询。更好的解决方案是使用注释,因此您可以在一个查询中完成所有操作。更改您的查询集以添加相关注释的带注释的计数:

from django.db.models import Count

class ArticlesListView(ListView):
    queryset = Article.objects.select_related().annotate(comment_count=Count('comments')).order_by('-dateposted').filter(draft=0)

现在你可以做

{{ article.comment_count }}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章