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
I suspect by far the biggest slowdown is that this will do 1 database query per node. The json rendering is trivial in comparison to the hundreds of round-trips to your database.
You should cache the children on each node so that those queries can be done all at once. django-mptt has a cache_tree_children() function you can do this with.
import json
from mptt.templatetags.mptt_tags import cache_tree_children
def recursive_node_to_dict(node):
result = {
'id': node.pk,
'name': node.name,
}
children = [recursive_node_to_dict(c) for c in node.get_children()]
if children:
result['children'] = children
return result
root_nodes = cache_tree_children(Node.objects.all())
dicts = []
for n in root_nodes:
dicts.append(recursive_node_to_dict(n))
print json.dumps(dicts, indent=4)
Custom json encoding, while it might provide a slight speedup in some scenarios, is something I'd highly discourage, as it will be a lot of code, and it's something that's easy to get very wrong.