user9466396
user9466396

Reputation: 21

django-mptt serialization return children nodes outside of parent node also

I am using django-mptt with django-rest-framework and for recursive serialization I am using djangorestframework-recursive package but it returns child node outside of parent node also. I have tried to_representation() also that leads to same result.

from rest_framework import serializers
from rest_framework_recursive.fields import RecursiveField
from .models import Category

class CategorySerializer(serializers.ModelSerializer):
    children = RecursiveField(many=True)

    class Meta:
        model = Category  
      fields = ('id','name','parent', 'children')

views.py

from rest_framework import generics
from .serializers import CategorySerializer
from .models import Category

class CategoryListAPI(generics.ListCreateAPIView):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

Output is

[   {
        "id": 1,
        "name": "Rock",
        "parent": null,
        "children": [
            {
                "id": 4,
                "name": "Corase Rock",
                "parent": 1,
                "children": []
            },
            {
                "id": 2,
                "name": "Hard Rock",
                "parent": 1,
                "children": []
            },
            {
                "id": 3,
                "name": "Soft Rock",
                "parent": 1,
                "children": []
            }
        ]
    },
    {
        "id": 4,
        "name": "Corase Rock",
        "parent": 1,
        "children": []
    },
    {
        "id": 2,
        "name": "Hard Rock",
        "parent": 1,
        "children": []
    },
    {
        "id": 3,
        "name": "Soft Rock",
        "parent": 1,
        "children": []
    }
]

Upvotes: 1

Views: 636

Answers (1)

user9466396
user9466396

Reputation: 21

I have solved this problem if anybody going through this I am answering here. There is an error in views.py file queryset should be:

queryset = Category.objects.root_nodes()

Upvotes: 1

Related Questions