【问题标题】:How to change serializer field name when validation error is triggered触发验证错误时如何更改序列化程序字段名称
【发布时间】:2020-08-28 03:33:18
【问题描述】:

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

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."
    ]
}

错误字典的键是字段名-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


    【解决方案1】:

    另一种解决方案是重写验证方法。

    def validate(self, data):
        self_description = str((data['self_description']))
        analyst_notes = str((data['analyst_notes']))
        if re.match(r'^[a-zA-Z0-9,.!? -/*()]*$', self_description) or re.match(r'^[a-zA-Z0-9,.!? -/*()]*$', analyst_notes):
            raise serializers.ValidationError({
                    "general_errors": [
                        "The system detected that the data is not in English. Please correct the error and try again."
                    ]
                })
        return data 
    

    【讨论】:

      【解决方案2】:

      解决方案非常简单。

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

      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',......)
      

      【讨论】:

      • 更改字段名称本身不太可接受,因为有很多其他逻辑与之相关。
      • @jekson 感谢您的评论。
      【解决方案3】:

      实现这一目标的一种方法是通过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'
      }
      

      【讨论】:

        猜你喜欢
        • 2017-09-01
        • 1970-01-01
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多