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)
获取某个节点下的tree结构(仍然只是一次查询)
from mptt.utils import get_cached_trees
query = SomeModel.objects.filter(con=True).get_descendants(include_self=True).all()
get_cached_trees(query)
网友评论