首页 > 解决方案 > 添加一个新函数来计算基于类的视图中的评论

问题描述

我正在尝试获取评论部分中的评论数量

我已将此功能添加到模型中以获取计数,但'ItemDetailView' object has no attribute 'comment'出现错误

class Comment(models.Model):
    STATUS = (
        ('New', 'New'),
        ('True', 'True'),
        ('False', 'False'),
    )
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ItemComments")
    comment = models.CharField(max_length=250, blank=True)
    status = models.CharField(max_length=10, choices=STATUS, default='New')

    def __str__(self):
        return '{} by {}'.format(self.subject, str(self.user.username))

    def total_comments(self):
        return self.comment.count()

我也将它包含在我认为可能是无法正常工作的原因的观点中

class ItemDetailView(DetailView):
    model = Item
    template_name = "product.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["comments"] = Comment.objects.filter(item=self.object, status='New')
        total_comments = self.comment.total_comments()
        context["total_comments"] = total_comments
        return context

这是模板

<h5><span>{{ total_comments }}</span> review for <span>{{object.title|capfirst }}</span></h5>

谢谢

标签: djangodjango-views

解决方案


这意味着,您的视图没有comment属性。您应该修改context_object_name

类ItemDetailView(DetailView):
    型号 = 项目
    template_name = "product.html"
    context_object_name = "评论"

或者您也可以使用self.object.total_comments()

但是,以前你不能.count()用于models.CharField字段,它应该是;

def total_comments(self):
    如果自我评论:
        返回 len(self.comment)
    返回 0

也许您想.count汇总当前过滤器的评论。如果是,您也可以修改您的 context_data。

def get_context_data(self, **kwargs):
    comments = Comment.objects.filter(item=self.object, status='New')
    context = super().get_context_data(**kwargs)
    context["comments"] = comments
    context["total_comments"] = comments.count()
    return context

推荐阅读