【问题标题】:Convert Validationerror to serializers.Validationerror in Django rest framework将 Validationerror 转换为 serializers.Validationerror 在 Django REST 框架中
【发布时间】:2020-08-25 00:11:33
【问题描述】:

我有以下问题。 我有一个模型级别的验证,它检查每次保存的数据一致性。 在序列化器中,如果这个模型级验证有效,它会生成带有回溯的server error 500,而序列化器中的serializer.Validationerror 会在json 中生成漂亮而干净的400 error

为了将模型级别 Validationerror 转换为 serializers. Validationerror,我在序列化程序中使用以下代码。

def perform_create(self, validated_data):
    try:
        return super().perform_create(validated_data)
    except exceptions.ValidationError as err:
        raise serializers.ValidationError(
            f'Model level validation assertion -- {str(err)}'
        ) from err

它有效,但我不能也不想覆盖每一个序列化程序以将 Validationerror 转换为 serializers. Validationerror

问题是 - 是否有任何方法可以捕获所有 Validationerror 并将它们转换为序列化程序。验证错误?

【问题讨论】:

  • 很好的问答。如果这个非常具体的场景由 DRF 处理,那就太好了。我很惊讶地看到这并没有困扰很多人。在another response here on SO 中提到在模型中实现验证时直接从rest_framework.exceptions 提高ValidationError,而不是django.core.exceptions 中的django.core.exceptions。这似乎对 API 和直接针对模型执行操作都非常有效。它还通过不必在序列化程序中重复验证来保持代码干燥。

标签: django-rest-framework


【解决方案1】:
from rest_framework.views import exception_handler
from rest_framework.response import Response as DRF_response
from rest_framework import status

from django.core import exceptions
from django.views import View
from django.http import response


def custom_exception_handler(exc: Exception, context: View) -> [response, None]:

    response = exception_handler(exc, context)

    if isinstance(exc, exceptions.ValidationError):
        data = exc.message_dict
        return DRF_response(data=data, status=status.HTTP_400_BAD_REQUEST, )

    return response

我制作了一个自定义错误处理程序,它捕获所有 Django 标准验证错误并返回 DRF 样式的响应。

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 2018-12-11
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多