diff --git a/boards/models/thread.py b/boards/models/thread.py --- a/boards/models/thread.py +++ b/boards/models/thread.py @@ -282,25 +282,41 @@ class Thread(models.Model): def get_reply_tree(self): replies = self.get_replies().prefetch_related('refposts') tree = [] - parent_positions = {} for reply in replies: parents = reply.refposts.all() + found_parent = False + searching_for_index = False + if len(parents) > 0: index = 0 + parent_depth = 0 + + indexes_to_insert = [] + for depth, element in tree: index += 1 + + # If this element is next after parent on the same level, + # insert child before it + if searching_for_index and depth <= parent_depth: + indexes_to_insert.append((index - 1, parent_depth)) + searching_for_index = False + if element in parents: found_parent = True - - offset_under_parent = parent_positions.get(element, 1) - tree.insert(index + offset_under_parent - 1, (depth + 1, reply)) - - # Move whole parent tree by 1 added element - for parent in parents: - parent_positions[parent] = parent_positions.get(parent, 1) + 1 + searching_for_index = True + parent_depth = depth if not found_parent: tree.append((0, reply)) + else: + if searching_for_index: + tree.append((parent_depth + 1, reply)) + + offset = 0 + for last_index, parent_depth in indexes_to_insert: + tree.insert(last_index + offset, (parent_depth + 1, reply)) + offset += 1 return tree