简体   繁体   中英

How to serialize JSON Request data from serializer in Django?

I am trying to serialize a json data through serializers.Serializer

{
    "data": {
        "phoneNumber": "1234567890",
        "countryCode": "+11",
        "otp": "73146",
    }
}

The sterilizer class I wrote for it

class VerifyOtpSerializer(serializers.Serializer):
    phone_number = serializers.CharField(max_length=225, source='phoneNumber', required=True)
    country_code = serializers.CharField(max_length=225, source='countryCode', required=True)
    otp = serializers.CharField(max_length=255, required=True)

在此处输入图像描述

and also

I don't know why source is not working, I tried the JSON in the picture below but still it's saying the field is required

在此处输入图像描述

source value is what the passed value's key will be changed into. So source value is expected to be on your Model .

The name of the attribute that will be used to populate the field.

What you really want is something that changes camel case payload into a snake case. Just use djangorestframework-camel-case and remove source from your serializer fields.

Your keys are wrong in the request. as Tom said the source should be an attribute of the model object. so you have to match keys in request and serializer

change phoneNumber > phone_number change countryCode > country_code

The response object you are are sending to your serializer is in correct. The key of your request object should be exactly what you have defined in your serializer.

Try sending this to your serializer.

{
    "data" : {
        "phone_number":"1234567890",
        "country_code":"+11", 
        "otp":"73146"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM