嵌套的序列化程序可以节省

时间:2018-08-23 07:51:41

标签: python django django-rest-framework

我正在尝试创建一个嵌套的序列化程序,以便也可以从父POST保存子序列。我有以下模型:

class Parent:
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=256)

class Child:
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=256)
    parent = models.ForeignKey(
        'Parent', null=True, on_delete=models.PROTECT, related_name='child_list')

然后是序列化器:

class ParentSerializer(serializers.ModelSerializer):
    child_list = ChildSerializer(many=True, read_only=True)

    class Meta:
        model = Parent
        fields = ('id', 'name', 'child_list')

    def create(self, validated_data):
        print(validated_data)
        rules_data = validated_data.pop('child_list')
        parent = Parent.objects.create(**validated_data)
        for rule_data in rules_data:
            Child.create(**rule_data)

        return parent

但是当我发布消息时出现错误

KeyError at /parent/
'child_list'

我想念什么吗?

1 个答案:

答案 0 :(得分:2)

在子列表上只读应该为假

child_list = ChildSerializer(many=True, read_only=False)