class Post(models.Model):
title = models.CharField(max_length=255)
category = models.ForeignKey(Category)
...
class Comment(models.Model):
body = models.TextField()
post = models.ForeignKey(Post)
...
视图
def single_post(request,slug):
p = Post.objects.get(slug=slug)
cat = Category.objects.all()
return render_to_response('single_post.html',{'p':p,'cat':cat},context_instance=RequestContext(request))
如何从模板中的单个帖子获取评论?
答案 0 :(得分:1)
在视图中:
def single_post(request,slug):
p = Post.objects.get(slug=slug)
cat = Category.objects.all()
comments = Comment.objects.filter(post=post)
return render_to_response('single_post.html',{'p':p,'cat':cat, 'comments':comments},context_instance=RequestContext(request))
在模板中,例如:
{% for comment in comments %}
{{ comment.body}}
{% endfor %}