Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 497
Jay Modi Avatar asked Aug 06 '15 10:08

Jay Modi


People also ask

How do you serialize an object in Django REST framework?

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.

What is serialization in Django REST framework?

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.

What is MPTT Django?

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.

Is serialization necessary in Django?

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.


1 Answers

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.

like image 89
Wannabe Coder Avatar answered Sep 20 '22 01:09

Wannabe Coder