Skip to main content
 首页 » 编程设计

python之在 Django View 中显示一对多关系

2025年05月04日46tuyile006

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

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 中执行此操作的正确方法是什么?

请您参考如下方法:

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

您的 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>