简体   繁体   中英

Django-mptt model serialize with Django REST framework

I have used django-mptt to store categories hierarchy and I need to serialize all category data in below format.

{
            "id": 1,
            "name": "FOOD"
            "children": [
                {
                    "id": 6,
                    "name": "PIZZA"
                },
                {
                    "id": 7,
                    "name": "BURGER"
                }
            ],

        },
        {
            "id": 2,
            "name": "ALCOHOL"
            "children": [
                {
                    "id": 8,
                    "name": "WINE"
                },
                {
                    "id": 9,
                    "name": "VODKA"
                }
            ],

        },
}

I'm using django REST framework ModelViewset and serializers. How to do so?

This response is a year too late, but for the benefit of others, use RecursiveField from the djangorestframework-recursive package , which can be installed via:

pip3 install djangorestframework-recursive

I was able to do it like so:

from rest_framework_recursive.fields import RecursiveField

class MyModelRecursiveSerializer(serializers.Serializer):
    # your other fields

    children = serializers.ListField(
        read_only=True, source='your_get_children_method', child=RecursiveField()
    ) 

Just be aware that this is potentially expensive, so you might want to only use this for models whose entries do not change that often and cache the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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