Django 模板:显示同一模型中的父项和子项

Django template: Displaying parent and child from the same model

我正在创建一个 Django 博客,我有一个 Comments 模型,如下所示:

class Comment(models.Model):
  content = models.TextField('Comment', blank=False, help_text='Comment * Required', max_length=500)
  post = models.ForeignKey('Post', on_delete=models.CASCADE, blank=False, related_name='comments')
  parent = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name='replies')

我正在尝试使用模板中的以下代码在评论下方显示回复:

{% for comment in comments %}
  {{ comment.content }}
  {% for reply in comment.replies.all %}
    {{ reply.content }}
  {% endfor %}
{% endfor %}

然而,这样做的结果是回复显示了两次。在他们自己相关的评论下方。 我究竟做错了什么?为什么回复显示两次。 此外,回复只能达到一个级别,即不能回复回复只能回复评论。

您需要在您的模板中进行检查,以便在回复有关联的父项时不显示回复(因为它们将显示在父项评论中)。你可以这样做:

{% for comment in comments %}
  {% if not comment.parent %}
      {{ comment.content }}
      {% for reply in comment.replies.all %}
        {{ reply.content }}
      {% endfor %}
  {% endif %}
{% endfor %}