Python 在Django视图中显示一对多关系
我正在制作一个django博客,希望为每个博客帖子显示一个评论列表,但我很难确定如何在视图和模板中引用评论。 我的模型定义如下:Python 在Django视图中显示一对多关系,python,django,Python,Django,我正在制作一个django博客,希望为每个博客帖子显示一个评论列表,但我很难确定如何在视图和模板中引用评论。 我的模型定义如下: class Issue(models.Model): title = models.CharField(max_length=255) text = models.TextField() author = models.ForeignKey(User) def __unicode__(self): return sel
class Issue(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
author = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Comment(models.Model):
commenter = models.ForeignKey(User)
issue = models.ForeignKey(Issue)
text = models.TextField()
{% for comment in issue.comment_set.all %}
{% include 'comment_detail.html' %}
{% endfor %}
<ul>
<li>{{ comment.issue }}</li>
<li>{{ comment.text }}</li>
</ul>
我的观点是这样的
class IssueDetail(DetailView):
model = Issue
context_object_name = "issue"
template_name = "issue_detail.html"
def get_context_data(self, **kwargs):
context = super(IssueDetail, self).get_context_data(**kwargs)
context['comments'] = Comment.objects.all()
return context
class CommentDetail(DetailView):
model = Comment
context_object_name = "comment"
template_name = "comment_detail.html"
最后是发布_detail.html模板
{% block content %}
<h2>{{ issue.title }}</h2>
<br/>
<i>As written by {{ issue.author.first_name }}</i>
<br/><br/>
<blockquote> {{ issue.text }}</blockquote>
<h3>Comments</h3>
{% for comment in comments %}
<li>{{comment}}</li>
{% endfor %}
{% endblock %}
{%block content%}
{{issue.title}
如{{issue.author.first_name}所写
{{issue.text}
评论
{注释%中的注释为%}
{{comment}}
{%endfor%}
{%endblock%}
这允许我引用问题模板内的注释字段,但基本上我希望注释有自己的模板,该模板将在for循环内呈现。在Django中执行此操作的正确方法是什么?由于您定义的模型关系,
注释在您的模板中已经可用。您可以在IssueDetail
中删除get\u context\u数据
您的issue\u detail.html
模板可能如下所示:
class Issue(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
author = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Comment(models.Model):
commenter = models.ForeignKey(User)
issue = models.ForeignKey(Issue)
text = models.TextField()
{% for comment in issue.comment_set.all %}
{% include 'comment_detail.html' %}
{% endfor %}
<ul>
<li>{{ comment.issue }}</li>
<li>{{ comment.text }}</li>
</ul>
您的comment\u detail.html
模板可能如下所示:
class Issue(models.Model):
title = models.CharField(max_length=255)
text = models.TextField()
author = models.ForeignKey(User)
def __unicode__(self):
return self.title
class Comment(models.Model):
commenter = models.ForeignKey(User)
issue = models.ForeignKey(Issue)
text = models.TextField()
{% for comment in issue.comment_set.all %}
{% include 'comment_detail.html' %}
{% endfor %}
<ul>
<li>{{ comment.issue }}</li>
<li>{{ comment.text }}</li>
</ul>
- {{comment.issue}
- {{comment.text}
我喜欢stackoverflow上的现成解决方案,它比阅读django的文档要好