简体   繁体   中英

How to query a tree structure in Django model

I have the following tree structure in Django Model

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? 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. 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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM