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
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)