我正在使用 django==1.8 和 DRF==3.3.2 并且我刚刚在我的项目中编写了自定义验证器,并且注意到 django.core 和 restframework 的 ValidationError 异常在 DRF 中同样有效。我认为这是由于rest_framework.fields中的这段代码:
from django.core.exceptions import ValidationError as DjangoValidationError
from rest_framework.exceptions import ValidationError
...
def run_validators(self, value):
"""
Test the given value against all the validators on the field,
and either raise a `ValidationError` or simply return.
"""
errors = []
for validator in self.validators:
if hasattr(validator, 'set_context'):
validator.set_context(self)
try:
validator(value)
except ValidationError as exc:
# If the validation error contains a mapping of fields to
# errors then simply raise it immediately rather than
# attempting to accumulate a list of errors.
if isinstance(exc.detail, dict):
raise
errors.extend(exc.detail)
except DjangoValidationError as exc:
errors.extend(exc.messages)
if errors:
raise ValidationError(errors)
如您所见,这两个异常都可以被 DRF 捕获,因此您可以在 django 表单和 DRF 中使用 django.core.exceptions.ValidationError。