问题描述:

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.

I was able to do it like so:

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.

相关阅读:
Top