[英]How to query a tree structure in Django model
I have the following tree structure in Django Model 我在Django模型中具有以下树结构
Main_Comment
id
comment_list [Comment]
Comment
id
parent_comment [Main_Comment or Comment]
child_comment_list [Comment]
How would you traverse the entire tree in Django query if given a main_comment id? 如果给出main_comment ID,您将如何遍历Django查询中的整个树? I know you could retreive all table and filter by main_comment if all Comment model instance have a main comment, but I want to preserver the nested structure of the nested comment. 我知道如果所有Comment模型实例都具有主注释,则可以检索所有表并按main_comment进行过滤,但是我想保留嵌套注释的嵌套结构。 Is there a way of doing that? 有办法吗?
Specifically for your model, if you wish to use Django query you can try a recursive approach to read all comments given the main_comment_id 专门针对您的模型,如果您希望使用Django查询,则可以尝试递归方法来读取给定main_comment_id的所有注释
The following is a depth-first way to query your tree structure 以下是深度优先的查询树结构的方法
main_comment = Main_Comment.objects.get(id=main_comment_id)
current_depth = 0
tree_comments = traverse_comments(main_comment, current_depth)
def traverse_comments(comment, depth)
if comment.comment_list.length == 0:
return [{comment: comment, depth: depth}]
else:
traversed_comments = [{comment: comment, depth: depth}]
new_depth = depth + 1
for child_comment in comment.comment_list:
traversed_comments = traversed_comments +traverse_comments(child_comment, new_depth)
return traversed_comments
For this to work you need to edit your Comment model columns naming to this: 为此,您需要编辑注释模型列,命名为:
Comment
id
parent_comment [Main_Comment or Comment]
comment_list [Comment]
You can also use raw sql queries using Django as well Check this out, might be helpful: https://github.com/Husseny/treebirds Check the models.py file inside nestedcomments/ 您也可以使用Django来使用原始SQL查询。检查一下,可能会有所帮助: https : //github.com/Husseny/treebirds检查nestedcomments /中的models.py文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.