Django,如何在模板中显示对该评论的评论和回复

D D*_*wal 6 django django-templates

我有一个注释表,它有一个表的外键Blog。此表用于对博客发表评论,并且可以对评论进行回复。为此,我使用了列parent来决定回复的评论。

现在的问题是这个表的对象,

comment_obj = comment.objects.filter(blog=blog_obj).order_by("created")
Run Code Online (Sandbox Code Playgroud)

我没有得到所需的输出。我想知道如何显示评论以及在每个评论下对该评论的回复。

模型.py:

class Comment(models.Model):
    user = models.ForeignKey(User_info)
    blog = models.ForeignKey(Blog)
    parent = models.ForeignKey('self', null=True)
    comment = models.CharField(max_length=500)
    status = models.CharField(max_length=1, default='A')
    created = models.DateTimeField(auto_now_add=True)
Run Code Online (Sandbox Code Playgroud)

模板:

{% for comment in comment_obj %}
    <li>
        {{ comment.comment }} - {{ comment.created }}
        {% for reply in comment.Comment_set.all %}
        <ul>
            {{ reply.comment }} - {{ reply.created }}
        </ul>
       {% endfor %}
    </li>
    {% endfor %}
Run Code Online (Sandbox Code Playgroud)

但这是行不通的。请帮忙。我想在不使用任何应用程序的情况下执行此操作。

Aam*_*nan 8

添加related_name使用可选的参数去的ForeignKey的,使事情变得更简单:

class comment(models.Model):
    user = models.ForeignKey(User_info)
    blog = models.ForeignKey(Blog, related_name='comments')
    parent = models.ForeignKey('self', null=True, related_name='replies')
Run Code Online (Sandbox Code Playgroud)

模板:(假设blog_objBlog对象)

{% for comment in blog_obj.comments.all %}
    {{ comment.comment }}
    {% for reply in comment.replies.all %}
        {{ reply.comment }}
    {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)