Search code examples
pythondjangodjango-rest-frameworkdjango-serializer

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)

enter image description here

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

enter image description here


Solution

  • 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.