DjangoRestFramework ModelSerializer: field-level validation is not working

天涯浪子 提交于 2019-12-05 09:42:28

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!