django 多对一场自身关系

vh0rcniy  于 2023-02-20  发布在  Go
关注(0)|答案(1)|浏览(88)

我用了一个self关系内的模型与foreignkey,目的是使一个可回复的评论,但idk如何使用它在模板中,我的意思是什么之间的不同3 ManyToOne关系我用在模板中,我怎么知道形式发送回复或评论?模型:

class Comment(models.Model):
    #comments model
    post = models.ForeignKey(Post,related_name='comments',on_delete=models.CASCADE)
    text = models.CharField(max_length=300)
    user = models.ForeignKey(get_user_model(),related_name='users',on_delete=models.CASCADE)
    date = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey('self', null=True,related_name='reply',on_delete=models.SET_NULL)

    class Meta():
        verbose_name_plural = 'Comments'
        ordering = ['date']
    
    def __str__(self):
        return self.test[:50]

模板:

<div>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button value="submit">Send</button>
    </form>
</div>

<div>
    {% for comment in object.comments.all %}
        <p>{{ comment.text }}</p>
        {% for reply in object.reply.all %}
            <p>{{ reply.text }}</p>
        {% endfor %}
        <form method='post'>
            {% csrf_token %}
            {{ form.as_p }}
            <button value="submit">reply</button>
        </form>
    {% endfor %}
</div>
{% endblock %}

你能稍微解释一下它是怎么工作的吗?

hgb9j2n6

hgb9j2n61#

您可以考虑在代码中使用with模板标记来使用递归解决方案,如下所示:
首先定义一个用于呈现注解的模板:

<!-- comments.html -->
{% for comment in comments %}
    <p>{{ comment.text }}</p>
    <form method='post'>
        {% csrf_token %}
        {{ form.as_p }}
        <button value="submit">reply</button>
    </form>
    {% if comment.reply.exists %}
        <ul>
            {% include "comments.html" with comments=comment.reply.all %}
        </ul>
    {% endif %}
{% endfor %}

然后将其包含在原始模板中:

<div>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button value="submit">Send</button>
    </form>
</div>

<div>
   {% include "comments.html" with comments=object.comments_only %}
</div>

最后,只发送没有父母的评论,像这样:

class Post(...):
   ...
   def comments_only(self):
      return self.comments.filter(parent__isnull=True)

相关问题