Sta*_*ato 3 django django-templates django-views django-class-based-views
我正在构建一个新闻应用程序,允许成员对文章发表评论。我想在我的模板中显示文章,并显示对每篇文章发表的评论数。我尝试使用 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 %}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我看到的所有示例都手动提供了一个过滤依据(例如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
Run Code Online (Sandbox Code Playgroud)
我的预期结果是在每篇文章下方列出所有文章和对该文章发表的评论汇总(例如第 1 条:4 条评论,第 5 条:1 条评论等...)现在我得到: 第 1 条:4 条评论,第 5 条:4 条评论(尽管第 5 条只有 1 条评论)
任何帮助表示赞赏。我花了 5 个小时通读文档,但每个示例都手动提供了一个过滤依据。
我不知道为什么你觉得这出乎意料。comments是所有评论,所以当然comments.count是所有评论的计数。不然怎么可能?你不会在任何地方过滤它们。
然而,这是一种非常可怕的做事方式。绝对没有理由将所有评论传递给模板,然后遍历它们以检查它们是否是正确的文章。你有一个从 Comment 到 Article 的外键,所以你应该使用反向关系来获取相关的评论。
从您的视图中完全删除 Comment 查询,并在您的模板中执行此操作(替换整个嵌套的 fors 和 ifs 块):
{{ article.comment_set.count }}
Run Code Online (Sandbox Code Playgroud)
然而,这对每篇文章进行一次计数查询。更好的解决方案是使用注释,这样您就可以在一个查询中完成所有操作。更改您的查询集以添加相关评论的注释计数:
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)
Run Code Online (Sandbox Code Playgroud)
现在你可以做
{{ article.comment_count }}
Run Code Online (Sandbox Code Playgroud)