def to_tree(self): cache_key = 'menu-tree-%s' % self.slug root = cache.get(cache_key) if not root: item = root = Item(self) descendents = self.get_descendants() for prev, curr, next in previous_current_next(descendents): previous_item = item item = Item(curr) if not prev or prev.level < curr.level: previous_item.add_child(item) elif prev and prev.level > curr.level: parent = previous_item while parent.node.level >= curr.level: parent = parent.parent parent.add_child(item) else: previous_item.parent.add_child(item) cache.set(cache_key, root) return root