django:阻止Serializer上的UniqueTogetherValidator

时间:2016-05-12 09:54:22

标签: python django api django-validation

我遇到了django的问题。我用一些字段创建了我的模型:

class MyModel(Model):
    field1 = models.IntegerField()
    field2 = models.CharField(max_length=200)
    field3 = models.IntegerField()

    class Meta:
        unique_together = (('field1', 'field2'))

我有一个API路由,链接到模型序列化器:

class MyModelSerializer(ModelSerializer):
    class Meta:
        model = models.MyModel

问题在于,当我通过API发送对象来更新它们时,序列化程序会引发{'non_field_errors': ['The fields field1, field2 must make a unique set.']}

有谁知道如何阻止在序列化程序上使用UniqueTogetherValidator

1 个答案:

答案 0 :(得分:0)

这基于djangorestframework==3.8.2。 覆盖get_validators上的ModelSerializer方法,并注释掉获取unique_together_validators的调用,如果那是您真正关心的唯一验证器。否则,此答案https://stackoverflow.com/a/46022282/1658745建议仅将验证器设置为空列表,以关闭该序列化器的所有验证。

class MyModelSerializer(ModelSerializer):

    def get_validators(self):
        """
        Determine the set of validators to use when instantiating serializer.
        """
        # If the validators have been declared explicitly then use that.
        validators = getattr(getattr(self, 'Meta', None), 'validators', None)
        if validators is not None:
            return validators[:]

        # Otherwise use the default set of validators.
        return (
            # self.get_unique_together_validators() +
            self.get_unique_for_date_validators()
        )

    class Meta:
        model = models.MyModel