Why serializer.validators returns [] in your case?
This is happening because you have not passed a validators arguments to the serializer when creating an instance of the serializer. Had you passed the validators argument, then serializer._validators would be set to that value. Then, if you check serializer.validators, it would give you the list of validators passed.
For Example:
In [1]: serializer = SomeSerializer(data=some_data, validators=[validator1, validator2])
In [2]: serializer.validators
Out [2]: [validator1, validator2] # gives the list of validators
By default, [] is returned if no validators is passed when accessing serializer.validators.
Source code for reference:
Now, BaseSerializer inherits from Field class which calls its __init__().
class BaseSerializer(Field):
def __init__(self, instance=None, data=empty, **kwargs):
...
super(BaseSerializer, self).__init__(**kwargs)
Here, default_validators is an empty list [].
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
Why your code shows error for invalid data then?
This is because field-level validators are causing that error. Your serializer-level validators is [] but there are some field-level validators which are raising error for invalid data.
To see field-level validators, you can do print repr(serializer).
validatorsattribute. Did you tryget_validators()? Also, I usually find what I need to know from reading the source. github.com/tomchristie/django-rest-framework/blob/master/…validatorsare in this linefor validator in self.validators:in line 488, I triedget_validatorsafter you mentioned it, and still got[]when I print it out, which is weird because I can see that when I pass invalid data in it will return errorsFieldobjects, not aSerializerobject.class BaseSerializer(Field):line 58 , I also checked the serializer class, it seems like there is no validator besides the one inherited from Field?