django-mptt 如何只用一次查询遍历所有节点获取一颗tr

2019-05-08  本文已影响0人  guoliu
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)
上一篇 下一篇

猜你喜欢

热点阅读