drs
drs

Reputation: 23

Assign JSON field to model variable in django

I am having my json like:

{
   "name": "Rahul",
   "2or4": 2,

}

Here,

How can I assign my model variable : twoOrFour to jason field value "2or4" as we can not have variable start with integer.

I am new to django. I am using dJango-rest-framework for this api.

Upvotes: 1

Views: 1185

Answers (2)

Ramast
Ramast

Reputation: 7709

If you are using djangorestframework you will need to override to_representation function in your serializer

http://www.django-rest-framework.org/api-guide/serializers/#overriding-serialization-and-deserialization-behavior

should be something like this

def to_representation(self, obj)
    serialized_data = super(SerializerClassName, self).to_representation(obj)
    serialized_data["2or4"] = serialized_data["twoOrFour"]
    //Remove the old field name
    del serialized_data["twoOrFour"]
    return serialized_data

This code should work where SerializerClassName is the class name of your serializer

Upvotes: 1

xyres
xyres

Reputation: 21734

You can try adding twoOrFour to your JSON object. For example:

import json

data = {'name': 'Rahul', '2or4': 2}

data = json.loads(data) # convert to Python dict
data['twoOrFour'] = data['2or4'] # append twoOrFour
data = json.dumps(data) # convert back to JSON object

Now the JSON object has twoOrFour field. Hope it works.

Upvotes: 0

Related Questions