【DRF-10】rest-framework之序列化(資料校驗)

Tony_xiao發表於2024-06-03
  • 1.自定義
class TitleValidator(object):
    def __init__(self,start):
        self.start = start

    def __call__(self, value):
        if not value.startswith(self.start):
            message = '標題必須以 %s 為開頭。' % self.start
            raise serializers.ValidationError(message)

    def set_context(self, serializer_field):
        """
        This hook is called by the serializer instance,
        prior to the validation call being made.
        """
        # 執行驗證之前呼叫,serializer_fields是當前欄位物件
        pass

class UserGroupSerializer(serializers.Serializer):
    title = serializers.CharField(error_messages={'required':'組名不能為空'},validators=[TitleValidator('test'),])

class UserGroupView(APIView):
    def post(self,request,*args,**kwargs):
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():
            print(ser.validated_data['title'])
            return HttpResponse("提交成功")
        else:
            print(ser.errors)   # {'title': [ErrorDetail(string='標題必須以 test 為開頭。', code='invalid')]}
            return HttpResponse(ser.errors)
  • 2.基於ModelSerializer
class TitleValidator(object):
    def __init__(self,start):
        self.start = start

    def __call__(self, value):
        if not value.startswith(self.start):
            message = '標題必須以 %s 為開頭。' % self.start
            raise serializers.ValidationError(message)

    def set_context(self, serializer_field):
        """
        This hook is called by the serializer instance,
        prior to the validation call being made.
        """
        # 執行驗證之前呼叫,serializer_fields是當前欄位物件
        pass

class UserGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserGroup
        fields = '__all__'
        depth = 1
        extra_kwargs = {'title': {'validators': [TitleValidator('test'), ]}}


class UserGroupView(APIView):

    def post(self,request,*args,**kwargs):
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():
            print(ser.validated_data['title'])
            return HttpResponse("提交成功")
        else:
            print(ser.errors)   # {'title': [ErrorDetail(string='標題必須以 test 為開頭。', code='invalid')]}
            return HttpResponse(ser.errors)
  • 3.鉤子函式
class UserGroupSerializer(serializers.Serializer):
    title = serializers.CharField()
    # 鉤子函式,validate + “_” + 欄位名稱
    def validate_title(self,value):
        if not value.startswith("test"):
            message = '標題必須以 test 為開頭'
            raise serializers.ValidationError(message)

class UserGroupView(APIView):

    def post(self,request,*args,**kwargs):
        ser = UserGroupSerializer(data=request.data)
        if ser.is_valid():
            print(ser.validated_data['title'])
            return HttpResponse("提交成功")
        else:
            print(ser.errors)   # {'title': [ErrorDetail(string='標題必須以 test 為開頭。', code='invalid')]}
            return HttpResponse(ser.errors)

相關文章