更新嵌套序列化程序时Django休息框架验证(many = True)

时间:2015-02-02 02:42:58

标签: django serialization django-rest-framework

我有以下型号:

class Child(models.Model):
    attr1 = models.CharField(max_length=20)
    attr2 = models.CharField(max_length=30)
    attr3 = models.BigIntegerField()

    class Meta:
        unique_together = ("attr1", "attr2", "attr3")

class Parent(models.Model):
    children = models.ManyToManyField(Child, related_name="parents")

然后是以下序列化程序:

class ChildSerializer(serializers.ModelSerializer):
    class Meta:
        model = Child

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer(many=True)
    class Meta:
        model = Parent

使用嵌套(多个= True)子序列化程序更新父实例时,出现验证错误:

The fields attr1, attr2, attr3 must make a unique set.

但是,不应该让序列化程序跳过子项的验证,因为他们已经从数据库中检索了实例?

2 个答案:

答案 0 :(得分:0)

Nested Serializers为我工作many=true。这是我的代码:

class ChildSerializer(serializers.ModelSerializer):
    parents = ChildSerializer(many=True)

    class Meta:
        model = Child
        fields = ('id', 'parents')

class ParentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Parent

父模型中有childern字段。在序列化程序中,您尝试在其中添加相同的字段。因此,它说场必须是独一无二的。

答案 1 :(得分:0)

通过覆盖to_internal_value的ParentSerialzer,可以“跳过”子序列化程序验证,或编写自定义序列化程序验证以覆盖子序列化程序:

class ParentSerializer(serializers.ModelSerializer):
    children = ChildSerializer(many=True)

    def to_internal_value(self, *args, **kwargs):
        try:
            # runs the child serializers
            return super().to_internal_value(*args, **kwargs)
        except ValidationError as e:
            # fails, and then overrides the child errors with the parent error
            return self.validate(self.initial_data)

    def validate(self, attrs):
        errors = {}
        errors['custom_override_error'] = 'this ignores, and overrides the children serializers'
        if len(errors):
            raise ValidationErrors(errors)
        return attrs
    class Meta:
        model = Parent
相关问题