DjangoRestFramework ModelSerializer: field-level validation is not working
Field-level validation is called before serializer-level validation.
So model User
having username as unique=True
, the field-level validation will raise exception because of username being already present. DRF's UniqueValidator
does this work of raising exception when a field is not unique.
As per DRF source code,
class UniqueValidator:
"""
Validator that corresponds to `unique=True` on a model field.
Should be applied to an individual field on the serializer.
"""
message = _('This field must be unique.')
Since these validators run before serializer-level validation, your validate_username
is never called.