django - 添加一个新函数来计算基于类的视图中的评论
问题描述
我正在尝试获取评论部分中的评论数量
我已将此功能添加到模型中以获取计数,但'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>
谢谢
解决方案
这意味着,您的视图没有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
推荐阅读
- vba - 滚动到表单中的子报表底部 (Access 2016)
- python - google vision api可以用来实现光学标记识别吗?
- powershell - Powershell 帮助。无法弄清楚出了什么问题
- powermockito - 如何为 google spanner 语句和 Statement Builder 创建模拟测试
- ansible - 使用 Ansible 复制特定文件
- linux - 如何处理 docker overlay/diff 目录中巨大的 .m2 目录?
- javascript - 如何调用 URL,将它返回的 JSON 传递给函数并循环遍历结果以记录名称
- c# - 命名空间“Quartz”中不存在类型或命名空间名称“Collection”
- r - 我如何找到连续的值
- firebase - 从 Firebase 控制台临时禁用新注册