1👍
I smell Tree structure here.
For this in Django you can use: django-mptt
It adds several columns to your table and a lot usefull stuff to work with your model as a tree structure.
And it claims to be very efficient
1👍
You could possibly add a function to the models module that traverses the comment tree and yields each comment in order, like so:
# Note this will work given either a Post or Comment object
def traverse_comment_tree(obj_with_comments):
for comment in obj_with_comments.comments.all():
yield comment
for descendant_comment in traverse_comment_tree(c):
yield descendant_comment
class Post(models.Model):
[...]
def all_comments(self):
return (c for c in traverse_comment_tree(self))
As an aside, note that traverse_comment_tree
is basically a pre-order depth-first traversal (with a Post
object as the tree root, so it is never “visited” as only Comment
objects are desired).
Then the template would work like this:
{% for comment in post.all_comments %}
{{ comment }}
{% endfor %}
All comments should then be traversed and output in the proper order (i.e. all descendants of one top-level comment are output before the next top-level comment). The next step would be to implement a way for the template to know which “level” of comment it is on.
This method, with a QuerySet call per comment, is inefficient of course; but hopefully it will help steer you in the right direction.