我正在学习一些教程,但是当教师说我应该将评论中的外键放到帖子上以便得到评论时,我们没有得到。而不是comment_set,我做了
#path = request.get_full_path()
#comments = Comment.objects.filter(path=path)
现在,当我不应该给孩子发表评论时,我会得到孩子评论。当我执行post.comment_set.all(),
而非上述两行时,我不会发表任何评论和此错误;'发布'对象没有属性' comment_set'
。有人可以澄清comments = post.comment_set.filter
的工作原理吗?这是我的完整代码。
models.py
class Comment(models.Model):
user = models.ForeignKey(MyProfile)
parent = models.ForeignKey("self", null=True, blank=True)
path = models.CharField(max_length=350)
post = models.ForeignKey(Post, null=True, blank=True, related_name="commented_post")
text = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
active = models.BooleanField(default=True)
objects = CommentManager()
class Meta:
ordering = ['-timestamp']
def __unicode__(self):
return self.text
def get_absolute_url(self):
return reverse('comment_thread', kwargs={"id": self.id})
@property
def get_origin(self):
return self.path
@property
def get_comment(self):
return self.text
@property
def is_child(self):
if self.parent is not None:
return True
else:
return False
def get_children(self):
if self.is_child:
return None
else:
return Comment.objects.filter(parent=self)
和我的views.py
#for single-post page
def post(request, slug):
user = get_object_or_404(User,username__iexact=request.user)
try:
profile = MyProfile.objects.get(user_id=request.user.id)
# if it's a OneToOne field, you can do:
# profile = request.user.myprofile
except MyProfile.DoesNotExist:
profile = None
post = get_object_or_404(Post, slug=slug)
post.views += 1 # increment the number of views
post.save() # and save it
#path = request.get_full_path()
#comments = Comment.objects.filter(path=path)
comments = post.comment_set.all()
comment_form = CommentForm(request.POST or None)
for c in comments:
c.get_children()
context_dict = {
'post' :post,
'profile' :profile,
'comments' : comments,
'comment_form':comment_form
}
return render(request, 'main/post.html', context_dict)
答案 0 :(得分:2)
Django支持所谓的"后向关系",它只是从实体对象向后访问子实体。让我们说我们有下一个模型:
class Post(models.Model):
#some fields
class Comment(models.Model):
post = models.ForeignKey(Post)
然后Django为您提供默认function以通过post.comment_set
语句访问Comment。但是,如果要在外键的注释中编写related_name选项,它会将此默认comment_set更改为...您在related_name选项中编写的内容。你可以阅读这个here。那就是你写的
post = models.ForeignKey(Post, null=True, blank=True, related_name="commented_post")
这意味着您必须通过
访问您的评论post.commented_post.all()
希望它有所帮助!