7

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?

Jay Modi
  • 3,161
  • 4
  • 35
  • 52
  • 1
    possible duplicate of http://stackoverflow.com/questions/21112302/how-to-serialize-hierarchical-relationship-in-django-rest. take a look at the answer suggested there. note that it is DRF2 specific so it might need to be adjusted for DRF3 – miki725 Aug 07 '15 at 20:10
  • Thanks, I tried that but didn't worked out. So can you help me further? – Jay Modi Aug 10 '15 at 05:08
  • I dont know any additional information then what is on that page. sorry – miki725 Aug 10 '15 at 12:09
  • Check my answer on a similar topic there: https://stackoverflow.com/a/65680073/4313735 – michal-michalak Jan 12 '21 at 08:10

1 Answers1

9

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.

Lord Elrond
  • 13,430
  • 7
  • 40
  • 80
Wannabe Coder
  • 1,457
  • 12
  • 21