从object_list(列表视图,Django)中为每个项目过滤另一个模型字段计数

时间:2018-11-25 11:20:21

标签: django listview filtering

我正在让Django尝试创建一个博客。我在首页上有Post模型的ListView。我正在尝试添加新的上下文数据(来自ListView的每个项目的单独模型Comment的注释数)。但是,我无法使用__in正确过滤每个帖子的评论数(它仅在ListView的每个帖子项上显示相同的评论总数)。您能帮助我如何获取正确的过滤器以显示每个ListView Post项目有多少评论吗?

谢谢!

发布模型:

class Post(models.Model):
    class Meta:
        verbose_name = 'запись'
        verbose_name_plural = 'записи'

    title = models.CharField('название', max_length=300, help_text='Не более 300 знаков')
    content = models.TextField('текст записи')
    date_posted = models.DateTimeField('дата публикации', default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='автор')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

评论模型:

class Comment(models.Model):
    class Meta:
        verbose_name = 'комментарий'
        verbose_name_plural = 'комментарии'

    content = models.CharField('текст комментария', max_length=500, help_text='Не более 500 знаков')
    date_posted = models.DateTimeField('дата публикации', default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name = 'автор')
    postid = models.ForeignKey(Post, on_delete=models.CASCADE)

views.py中的ListView:

class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['comments'] = Comment.objects.filter(postid__in = self.object_list)
        return context

我在html模板中使用的上下文数据:

{% for post in posts%}
 {{ post.content }}
 {{ comments.count }}
{% endfor %}

1 个答案:

答案 0 :(得分:1)

您可能想要的是.annotate(..)查询集,以便每个Post对象都包含一个带有注释数量的额外属性:

from django.db.models import Count

class PostListView(ListView):
    model = Post
    queryset = Post.objects.annotate(
        num_comments=Count('comment')
    )
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 5

然后,您可以在模板中获取.num_comment属性(此属性仅添加到源自 this Post的{​​{1}}对象中)并进行渲染它与:

queryset