python - 如何从 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 评论模型代码存储的评论。
我的任务:我有父评论的 id。我必须推导出 RED 框的其余部分。
欢迎任何东西:想法、SQL 脚本或 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)
@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.
推荐阅读
- javascript - 有没有办法使用空手道 DSL 获得 sessionStorage?
- xml - Powershell - XML - 如何从每个节点系列的不同深度提取多个值
- linux - 在周日某个时间之后和周五某个时间之前运行 cron 的干净方式
- excel - VBA使用文件中的参数列表查找/替换并在搜索字符串中包含空格
- c++ - std::function 模板参数推导
- javascript - 通过比较共享 value2 的元素的 value1 从数组中删除对象
- javascript - 是否可以在它所在的类之外的异步函数中传递数据?
- kotlin - 根据字段值反序列化为密封子类
- javascript - Onclick 在循环内单击所有元素
- python - 为什么用循环和公式在python中计算利率不同?