我正在创建一个包含一个视频的页面,尽可能多的评论,每个评论都会回复 我可以检索视频和评论,但最终检索到每个评论的回复。 我在视图文件中制作了一些for循环,但是也不知道如何在模板文件中检索它。 到现在为止,我一直困在视图和模板之间
我正在使用django 1.10.4
models.py
class Video(models.Model):
title = models.CharField(max_length=120)
embed_code = models.CharField(max_length=500)
slug = models.SlugField(null=True, blank=True)
category = models.ForeignKey("Category", null=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
active = models.BooleanField(default=True)
featured = models.BooleanField(default=False)
free_preview = models.BooleanField(default=False)
share_message = models.CharField(max_length=150, default=default_share_message)
objects = models.Manager()
# activemodel = ActiveModel()
featuresandactive = Features()
class Meta:
unique_together = ('slug', 'category')
def __str__(self):
return self.title
def get_absolute_url(self):
try:
return reverse('video_detail', kwargs={'vid_slug':self.slug, 'cat_slug':self.category.slug})
except:
return "/"
class Comment(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(MyUser)
path = models.CharField(max_length=350)
video = models.ForeignKey(Video, null=True, blank=True)
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()
def __str__(self):
return self.text
class Reply(models.Model):
user = models.ForeignKey(MyUser)
comment = models.ForeignKey(Comment,null=True, blank=True)
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 = ReplyManager()
def __str__(self):
return self.text
views.py
def video_detail(request, cat_slug, vid_slug):
cat = Category.objects.get(slug=cat_slug)
comments = Comment.objects.filter(video=obj)
replys = Reply.objects.filter(comment=comments)
context = {
"cat": cat,
"obj":obj,
"comments":comments,
"replys":replys,
}
return render(request, 'video_detail.html', context)
这是另一个view.py 我也尝试了这个但是没有工作
def video_detail(request, cat_slug, vid_slug):
cat = Category.objects.get(slug=cat_slug)
obj = Video.objects.get(slug=vid_slug)
comments = obj.comment_set.all()
Replies = Reply.objects.filter(comment_id=comments.id))
context = {
"cat": cat,
"obj":obj,
"comments":comments,
"replies":replies
}
return render(request, 'video_detail.html', context)
答案 0 :(得分:0)
IMO,您可以在模板中表示评论。您的模板可能如下所示。
# your_template.html
{% for comment in obj.comment_set.all %}
{{comment.user}}: {{comment.text}}
{% for reply in comment.reply_set.all %}
{{reply.user}}: {{reply.text}}
{% endfor %}
{% endfor %}
那么您的查看功能只需要cat
和obj
,而不是comments
或replies
。还可以查看select_related
。