我正在做博客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注释模型代码存储的注释。
我的任务:,我有父注释的id。我得推导出其余的红色盒子。
欢迎任何内容: Idea、SQL脚本或Django查询
发布于 2020-02-07 20:38:17
您可以在模型上添加一个名为“答复”的属性,它将在这些注释上给出所有答复。
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 11Update:如果直接需要所有嵌套的回复,则可以在删除对象期间执行类似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.https://stackoverflow.com/questions/60120573
复制相似问题