[英]How to make seperate comment section for each item
I am making django app I have a problem I dont have idea how to make seperate comment section to each Item.我正在制作 django 应用程序 我有一个问题 我不知道如何为每个项目制作单独的评论部分。 I do not want to have same comments for every Item on a page.
我不想对页面上的每个项目都有相同的评论。
models.py模型.py
class Comment(models.Model):
comment_user = models.OneToOneField(User, on_delete=CASCADE)
item = models.OneToOneField(Item, on_delete=CASCADE)
content = models.TextField(default='')
views.py视图.py
class ShopDetailView(DetailView):
model = Item
template_name = 'shop/detail.html'
context_object_name = 'item'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
return context
For a DetailView
, you can obtain the related comments with:对于
DetailView
,您可以通过以下方式获取相关评论:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['comments'] = Comment.objects.filter(item=self.object)
return context
It makes however not much sense to work with a OneToOneField
here, since that means that each item can only have at most one comment.然而,在这里使用
OneToOneField
没有多大意义,因为这意味着每个项目最多只能有一个评论。 You probably want a many-to-one relation, and thus work with a ForeignKey
[Django-doc] :你可能想要一个多对一的关系,因此使用
ForeignKey
[Django-doc] :
class Comment(models.Model):
comment_user = models.OneToOneField(User, on_delete=CASCADE)
item = models.ForeignKey(Item, on_delete=CASCADE)
content = models.TextField(default='')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.