Django Rest Framework序列化验证器始终为空

时间:2015-08-27 03:13:30

标签: python django django-rest-framework

我正在尝试打印django rest框架中的验证器列表,但是当我将其打印出来时,它似乎总是空的。

以下是代码的一部分

class AccountViewSet(viewsets.ModelViewSet):
    lookup_field = 'username'
    queryset = Account.objects.all()
    serializer_class = AccountSerializer


    def create(self, request):

        serializer = self.serializer_class(data=request.data)
        # this always return []
        print serializer.validators

这是违反直觉的,因为当我在request.data中测试无效数据时,代码显然会运行验证程序,因为is_valid()返回错误,如documentation所示。因此,我无法观察验证器生效但无法将其打印出来。有人可以指出我缺少的东西吗?

由于

1 个答案:

答案 0 :(得分:2)

为什么serializer.validators会在您的案例中返回[]

发生这种情况是因为在创建序列化程序实例时尚未向序列化程序传递validators个参数。如果您传递了validators参数,那么serializer._validators将被设置为该值。然后,如果您检查serializer.validators,它将为您提供传递的验证器列表。

例如:

In [1]: serializer = SomeSerializer(data=some_data, validators=[validator1, validator2])

In [2]: serializer.validators
Out [2]: [validator1, validator2] # gives the list of validators

默认情况下,如果在访问[]时未通过验证程序,则会返回serializer.validators

参考源代码:

现在,BaseSerializer继承自调用其Field的{​​{1}}类。

__init__()

此处,class BaseSerializer(Field): def __init__(self, instance=None, data=empty, **kwargs): ... super(BaseSerializer, self).__init__(**kwargs) 是一个空列表default_validators

[]

为什么您的代码会显示无效数据的错误?

这是因为字段级验证器导致该错误。您的序列化程序级验证程序为class Field(object): default_validators = [] # an empty list by default default_empty_html = empty initial = None def __init__(self, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False): ... # Here, it checks if validators argument was passed when creating the serializer instance # If you have passed, then `.validators` will be set to that value. if validators is not None: self.validators = validators[:] ... @property def validators(self): if not hasattr(self, '_validators'): # This will be executed as there was no validators passed in kwargs self._validators = self.get_validators() return self._validators @validators.setter def validators(self, validators): self._validators = validators def get_validators(self): return self.default_validators[:] # returns empty list ,但有一些字段级验证程序会引发无效数据的错误。

要查看字段级验证程序,您可以执行[]