AlASAD WAIL
AlASAD WAIL

Reputation: 825

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. 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?

Upvotes: 0

Views: 219

Answers (1)

SM1L3_B0T
SM1L3_B0T

Reputation: 85

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
Proof2

Upvotes: 2

Related Questions