在Django视图中显示一对多关系

时间:2014-02-23 00:41:34

标签: python django

我正在创建一个django博客,并希望显示每篇博文的评论列表,但我无法弄清楚如何在视图和模板中引用评论。 我的模型定义如下:

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()

和我的观点一样

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"

最后是issue_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 %}

这允许我引用Issue模板中注释的字段,但基本上我希望注释有一个自己的模板,它将在for循环中呈现。在Django中执行此操作的正确方法是什么?

1 个答案:

答案 0 :(得分:8)

由于您定义的模型关系,comments已在您的模板中可用。您可以删除get_context_data中的IssueDetail

您的issue_detail.html模板可能如下所示:

{% for comment in issue.comment_set.all %}
  {% include 'comment_detail.html' %}    
{% endfor %}

您的comment_detail.html模板可能如下所示:

<ul>
    <li>{{ comment.issue }}</li>
    <li>{{ comment.text }}</li>
</ul>