Loading

序列化器ser.validated_data、ser.initial_data、ser.data

1.ser.data
示例:在视图中返回序列化后的数据

return Response(serializer.data)

2.ser.validated_data

if serializer.is_valid():
  validated_data = serializer.validated_data

3.ser.initial_data
原始数据

4.示例:

class LoginPwdSerializer(serializers.Serializer):
    mobile = serializers.CharField(required=True, validators=[RegexValidator(r"\d{11}", message="格式错误")])
    password = serializers.CharField(required=True)

    def validate_mobile(self, value):
        exists = models.Company.objects.filter(mobile=value).exists()
        if not exists:
            raise ValidationError("手机号不存在")
        return value

    def validate_password(self, value):
        return md5(value)

class LoginPwdView(BaseView, APIView):
    def post(self, request):
        ser = LoginPwdSerializer(data=request.data)
        ser.is_valid(raise_exception=True)

        print(ser.validated_data)
        print(ser.initial_data)
        print(ser.data)
        # instance = models.Company.objects.filter(**ser.).first()

        return Response("ok")

image

posted @ 2024-10-05 18:13  一只大学生  阅读(3)  评论(0编辑  收藏  举报