是否可以在 Django-Rest-Framework 中合并 Model/Form 验证器?

Is it possible to merge a Model/Form validator in Django-Rest-Framework?

我注意到 Django form and model validators 应该引发一个 django.core.exceptions.ValidationError,它是 Exception 的直接子类。

然而,在 DRF 中,我的验证器预计会引发 rest_framework.exceptions.ValidationError,它 不是 Django 的后代(它源自 rest_framework.exceptions.APIException(Exception)).

让自己保持干燥,我怎样才能编写一次验证器,然后在 Django 表单和 DRF 序列化程序中使用它?

是一个相关问题,其中 DRF 没有捕捉到 Django 核心 ValidationError

我正在使用 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。