我正在将django-mptt与django-rest-framework一起使用,并且对于递归序列化,我正在使用djangorestframework-recursive程序包,但是它 还返回父节点之外的子节点。 我尝试过to_representation()也导致 结果相同。
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
输出为
[ {
"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": []
}
]
答案 0 :(得分:1)
如果有人在此回答,我已经解决了这个问题。 views.py文件queryset中应该存在错误:
queryset = Category.objects.root_nodes()