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?
Creating and Using Serializers To create a basic serializer one needs to import serializers class from rest_framework and define fields for a serializer just like creating a form or model in Django.
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types.
MPTT, or modified preorder tree traversal, is an efficient way to store hierarchical data in a flat structure. It is an alternative to the adjacency list model, which is inefficient.
It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With