django serializer is_valid()返回false

时间:2018-05-03 09:10:29

标签: python django django-rest-framework django-serializer

使用django 2.0.2       Python 3.4

MySerializers.py

class MySerializer(BaseSerializer):
    UserUID = serializers.CharField()
    DeviceUID = serializers.CharField()
    SessionId = serializers.CharField()

MyView.py

class MyVeiw(BaseViewSet):
    serializer_class = MySerializer

    def create(self, request, *args, **kwargs):
        serializer_class = MySerializer(data=request.data.dict())
        if serializer_class.is_valid():
            print(serializer_class.errors)
            return Response(0)
        else:
            return Response(1)

输入数据

{'SessionId': '222a282f-c3f8-46d2-8476-8d4ec627a477', 'UserUID': '62', 'DeviceUI
D': '25'}

serializer_class

 return MySerializer(data={'SessionId': '7c5d0530-8e54-42aa-91a0-ce8776c82490', 'Us
erUID': '64', 'DeviceUID': '27'}):
    UserUID = CharField()
    DeviceUID = CharField()
    SessionId = CharField()

serializer_class.initial_data

return {'UserUID': '65', 'DeviceUID': '28', 'SessionId': 'aecef14f-
       7f9d-4f01-bc1d-89514  8ab0c05'}

serializer_class.errors

return {}

is_valid()始终为false

为什么错误return empty list

我尝试过SessionId更改UUIDField()但不能正常工作

UserUIDDeviceUID更改IntegerField()但无法正常工作

我认为这个序列化器有效,为什么返回false

1 个答案:

答案 0 :(得分:0)

class MySerializer(BaseSerializer):更改为class MySerializer(Serializer):

正如贝尔布朗提到的那样;如果您继承自BaseSerialzier,则应自行定义to_internal_value

默认情况下,BaseSerializer会引发NotImplementedError

def to_internal_value(self, data):
    raise NotImplementedError('`to_internal_value()` must be implemented.')