数组中的 Django rest 框架序列化程序验证错误消息

Django rest framework serializer validation error messages in array

在从序列化程序中检索验证错误时,有没有办法获取错误消息数组而不是对象?

例如:

[
        "User with this email already exists.",
        "User with this phone number already exists."
]

而不是:

{
        "email": [
            "User with this email already exists."
        ],
        "phone_number": [
            "User with this phone number already exists."
        ]
}

是的,你可以,你必须检查序列化程序是否无效,然后使用 for 循环迭代 error_dict 的键并将值附加到列表和 return 列表

serializer = YourSerializer(data={"email":"abc@gmail.com", "phone_number": "1234566"})
if serializer.is_valid():
    serializer.save()
else:
    error_list = [serializer.errors[error][0] for error in serializer.errors]
    return Response(error_list)

如果您想按照您提到的方式处理应用程序的任何序列化程序中的异常,您可以在您的应用程序目录下编写自己的自定义异常处理程序(例如my_project/my_app/custom_exception_handler):

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    """ Call REST framework's default exception handler first, to get the standard error response.
    """
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        # Place here your code
        errors = response.data
        ...

        # return the `response.data`
        # response.data['status_code'] = response.status_code
    return response

之后更新 settings.py 中的 EXCEPTION_HANDLER 值:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.custom_exception_handler'
}

DRF docs

中查看更多详细信息