device_data.get()始终返回Null

时间:2015-11-26 00:36:26

标签: python django django-rest-framework

嗨我正在尝试从JSON格式获取令牌,当我制作.get('gtoken')时他们返回NULL并且我不知道为什么

以下是我来自Serializers.py的代码

    class DeviceSerializer(serializers.Serializer):
    class Meta:
        model = Device
        fields = (
            'gtoken'
            )

class AddDeviceSerializer(serializers.Serializer):
    username = serializers.CharField()
    device = DeviceSerializer()
    class Meta():
        fields = (
            'username'
            'device'
            )

    def create(self, validated_data):
        """
        Add Device to an user
        """
        device_data = validated_data.pop('device')
        user = User.objects.get(username=validated_data['username'])
        gtoken = device_data.get('gtoken')
        device = Device.objects.create(gtoken = gtoken)
        device.user.add(user)
        return device

这就是我发送的内容

{
    "username": "735062",
    "device": {
        "gtoken": "cJHdNYxqIr4:APA91bFqFmFLoyf6t36iXAE9aoiSnG_nv8u5f6SfLVLrCtRYslAz04IZXfweLYg2RKRcQdJ6Vu0e9mLDFb2QB2k63oMnerKxSCfxO4PHmXrEQv_Pk-iWVlCsfoLYygat6OyPuiF79Gl1"
    }
}

该视图仅保存设备并且它正在工作,因为divice存储在DataBase中但没有TOKEN。

class UserDeviceToken(APIView):
    authentication_classes = (TokenAuthentication,)    
    permission_classes = (IsAuthenticated,) 

    def put(self, request):
        serializer = AddDeviceSerializer(data = request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(status=status.HTTP_201_CREATED)

注意设备是具有用户ManytoManyField关系的模型,其中Null = True,这就是为什么不发送和错误。

1 个答案:

答案 0 :(得分:1)

您希望DeviceSerializer成为ModelSerializer,因为Meta定义了model

目前,这是一个没有任何定义字段的常规Serializer。因此它不会返回任何数据。