[Answer]-How to query a tree structure in Django model

1👍

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/

Leave a comment