fastest way to create JSON to reflect a tree structure in Python / Django using mptt

后端 未结 4 1491
别跟我提以往
别跟我提以往 2021-01-30 14:54

What\'s the fastest way in Python (Django) to create a JSON based upon a Django queryset. Note that parsing it in the template as proposed here is not an option.

The ba

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-30 15:09

    After playing around with this a bit, I found that the solutions were all too slow, because mptt itself is scanning the cache multiple times to get_children.

    Capitalizing on the fact that mptt returns rows in the correct order to easily build trees, I made this:

    def flat_tree_to_dict(nodes, max_depth):
        tree = []
        last_levels = [None] * max_depth
        for n in nodes:
            d = {'name': n.name}
            if n.level == 0:
                tree.append(d)
            else:
                parent_dict = last_levels[n.level - 1]
                if 'children' not in parent_dict:
                    parent_dict['children'] = []
                parent_dict['children'].append(d)
            last_levels[n.level] = d
        return tree
    

    For my data set, this runs 10x faster than other solutions because it's O(n), only iterating the data once.

    I use it like this:

    json.dumps(flat_tree_to_dict(Model.objects.all(), 4), indent=4)
    

提交回复
热议问题