触发验证错误时如何更改序列化器字段名称

问题描述 投票:0回答:2

我需要更改验证字段时显示的错误的视图。

serializer.py

class ElementCommonInfoSerializer(serializers.ModelSerializer):

    self_description = serializers.CharField(required=False, allow_null=True,
                                             validators=[RegexValidator(regex=r'^[a-zA-Z0-9,.!? -/*()]*$',
                                                                        message='The system detected that the data is not in English. '
                                                                                'Please correct the error and try again.')]
                                             )
    ....

    class Meta:
        model = Elements
        fields = ('self_description',......)

显示此错误

{
    "self_description": [
        "The system detected that the data is not in English. Please correct the error and try again."
    ]
}

错误dict的关键是字段名称-self_description。对于FE,我需要发送其他格式,例如:

{
    "general_errors": [
        "The system detected that the data is not in English. Please correct the error and try again."
    ]
}

如何更改?

django django-rest-framework django-serializer django-validation
2个回答
1
投票

可以通过custom exception handler实现的一种方法

from copy import deepcopy
from rest_framework.views import exception_handler


def genelalizing_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 'self_description' in response.data:
        data = deepcopy(response.data)
        general_errors = data.pop('self_description')
        data['general_errors'] = general_errors
        response.data = data

    return response

在设置中

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils. genelalizing_exception_handler'
}

0
投票

解决方案非常简单。

您可以使用序列化器方法(源属性)重命名键字段您可以在下面找到示例代码。

** class QuestionSerializer(serializers.ModelSerializer):

question_importance = serializers.IntegerField(source='importance')
question_importance = serializers.IntegerField(required=False)
class Meta:
    model = create_question
    fields = ('id','question_importance','complexity','active')**

[上面您可以看到Django模型中存在一个重要字段,但是在这里我使用source属性将该字段重命名为question_importance。您的情况将如下所示,

Class ElementCommonInfoSerializer(serializers.ModelSerializer):

general_errors   = serializer.CharField(source="self_description")  
general_error    =    serializers.CharField(required=False, allow_null=True,
                                       validators=[])    
class Meta:
     model = Elements
     fields = ('general_error',......)
© www.soinside.com 2019 - 2024. All rights reserved.