我注意到Django form and model validators应该引发django.core.exceptions.ValidationError
,这是Exception
的直接子类。
然而,在DRF中,我的验证器应该会引发rest_framework.exceptions.ValidationError
,这是不是 Django的后代(它来自{{1} })。
保持干燥,我怎样才能编写一次验证器,并在Django表格和DRF序列化器中使用它?
Here是一个相关的问题,其中DRF没有捕获Django核心rest_framework.exceptions.APIException(Exception)
答案 0 :(得分:0)
我正在使用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。