Django-mptt serial model using Django REST framework

I have used django-mptt to store a category hierarchy and I need to serialize all category data in the following 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 am using django REST framework ModelViewset and serializers. How to do it?

+3


source to share


1 answer


This answer is too long, but for others, use RecursiveField

from djangorestframework-recursive package .

I was able to do it like this:



class MyModelRecursiveSerializer(serializers.Serializer):
    # your other fields
    children = serializers.ListField(read_only=True, source='your_get_children_method', child=RecursiveField()) 

      

Just keep in mind that this is potentially expensive, so you can only use it on models whose records don't change often and cache the results.

+5


source







All Articles