首页 > 解决方案 > 如何从 django 中的表中检索 comment_replies

问题描述

我正在做博客 API 的评论部分。我无法得到回复,但我可以得到评论。

Python模块:Django:

class Comment(models.Model):
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    comment = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey(
        'self', related_name='reply', null=True, blank=True,
        on_delete=models.CASCADE)

上面显示的 Django 代码的数据库表

上面的表格显示了使用 Django 评论模型代码存储的评论。

我的任务:我有父评论的 id。我必须推导出 RED 框的其余部分。

欢迎任何东西:想法、SQL 脚本或 Django 查询

标签: pythonsqldjango

解决方案


您可以在名为“回复”的模型上添加一个属性,它将对这些评论进行所有回复。

class Comment(models.Model):
    author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
    comment = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
    parent = models.ForeignKey(
        'self', related_name='reply', null=True, blank=True,
        on_delete=models.CASCADE)

    @property
    def replies(self):
        return Comment.objects.filter(parent_id=self.id)

因此,让我们假设您有一个父评论,并且您需要对该评论的所有回复

parent = Comment.objects.get(id=1)
# Replies on this comment is.
print(parent.replies) # It will have only one comment in array with id=9

现在,如果您需要回复评论id=9

parent.replies[0].replies # It will give comments with id 10 and 11

更新:如果您直接需要所有嵌套回复,您可以在删除对象期间执行类似于 Django-admin 的操作。它首先向您显示所有受影响的对象

from django.contrib.admin.utils 
collector = NestedObjects(using='default')
collector.collect(parents)
print(collector.data[parents[0].__class__]) # It will print all nested objects comments.


推荐阅读