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

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

作者: guoliu | 来源:发表于2019-05-08 11:47 被阅读0次
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)

相关文章

网友评论

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

      本文链接:https://www.haomeiwen.com/subject/xfgpoqtx.html