我正在做博客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 Comment模型代码存储的注释。
我的任务:我有父注释的ID。我必须推导红色框的其余部分。
欢迎任何东西:想法,SQL脚本或Django查询
您可以在名为“ replies”的模型上添加一个属性,它将对这些注释给出所有答复。
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句