简体   繁体   English

Django MPTT 查询集到嵌套字典,无需递归调用

[英]Django MPTT Queryset to nested dictionary without recursive calling

The Django MPPT is smart library that make only single query to get all nested data. Django MPPT是智能库,仅进行一次查询即可获取所有嵌套数据。 Is there a way to get the data as nested dictionary without recursive calling.有没有办法在没有递归调用的情况下将数据作为嵌套字典获取。

queryset = MyTreeModel.objects.values()
results = get_nested_dict(queryset) ???
results >>
{
            'id': 7,
            'name': 'parent',
            'children': [
                {
                    'id': 8,
                    'parent_id': 7,
                    'name': 'child',
                    'children': [
                        {
                            'id': 9,
                            'parent_id': 8,
                            'name': 'grandchild',
                        }
                    ]
                }
            ]
        }

How to create get_nested_dict() without recursive calling?如何在没有递归调用的情况下创建 get_nested_dict()?

My category hierarchy我的类别层次结构

from .models import Category
from mptt.utils import get_cached_trees

categories_list = Category.objects.all().order_by('name')


def get_nested_dictionary(queryset):
    roots = get_cached_trees(queryset)

    def form_a_tree(objects):
        tree = []

        for obj in objects:
            children = obj.get_children()
            dictionary_category_tree = {'id': obj.id, 'name': obj.name}
            if children:
                dictionary_category_tree.update({'children': form_a_tree(children)})
            tree.append(dictionary_category_tree)

        return tree

    return form_a_tree(roots)

Result:结果:

[
    {
        "id": 9,
        "name": "C++",
        "children": [
            {
                "id": 10,
                "name": "C++ for beginners"
            }
        ]
    },
    {
        "id": 5,
        "name": "JS",
        "children": [
            {
                "id": 7,
                "name": "JS for beginners"
            }
        ]
    },
    {
        "id": 1,
        "name": "Python",
        "children": [
            {
                "id": 2,
                "name": "Python for beginners",
                "children": [
                    {
                        "id": 4,
                        "name": "some subcategory"
                    },
                    {
                        "id": 6,
                        "name": "some subcategory2"
                    }
                ]
            }
        ]
    }
]

My solution makes only one query to db我的解决方案只对数据库进行一次查询
Proof1证明1
Proof2证明2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM