Django REST Framework POST具有自引用模型的嵌套数据

时间:2019-03-21 18:50:15

标签: python-3.x django-rest-framework nested recursive-query

我正在尝试创建REST API,以发布用于自引用模型的嵌套数据。 所以我创建了这些序列化器

class RecursiveField(serializers.Serializer):
    def to_representation(self, value):
        serializer = self.parent.parent.__class__(value, context=self.context)
        return serializer.data

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

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



    def create(self, validated_data):
        def create_children(children, parent):
            for child in children:
                if 'children' in child.keys():
                    categories = child.pop('children')
                else:
                    categories = []
                category = Category.objects.create(parent=parent, **child)
                if categories:
                    create_children(categories, category)
        if 'children' in validated_data.keys():
            categories = validated_data.pop('children')
        else:
            categories = []
        category = Category.objects.create(**validated_data)
        if categories:
            create_children(categories, category)
        return category

但是当我尝试发布数据

    {
"name": "Category A" ,
"children": [
{
"name": "Category A.A" ,
"children": [
{
"name": "Category A.A.A" ,
"children": [
{
"name": "Category A.A.A.A"
},
{
"name": "Category A.A.A.B"
}
]
}
]
}

我有问题:

  

/ categories / UNIQUE约束处的IntegrityError失败:   quickstart_category.name

并且从db病获得数据有:

{
    "count": 2,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 1,
            "name": "Category A",
            "children": [
                {
                    "id": 2,
                    "name": "",
                    "children": []
                }
            ]
        },
        {
            "id": 2,
            "name": "",
            "children": []
        }
    ]
}

0 个答案:

没有答案