【问题标题】:Adding a new function to count comments in a Class based view在基于类的视图中添加一个新功能来计算评论
【发布时间】:2020-07-01 03:25:23
【问题描述】:

我正在尝试在我的评论部分获取 cmets 的计数

我已将此功能添加到模型中以获取计数,我收到'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>

谢谢

【问题讨论】:

    标签: django django-views


    【解决方案1】:

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

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

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

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

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

    也许您想.count 当前过滤器的总 cmets。如果是,您也可以修改您的 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      相关资源
      最近更新 更多