Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update model field from json data?

Tags:

django

i have json data like:

{
"firstname": "nav",
"lastname": "yad",
"age": 22
}

I have defined a custom method for model Geek to save it from json object.

def jsonToModel(self, jsonObj): 
    data = json.loads(jsonObj)
    self.firstname = data['firstname']
    self.lastname = data['lastname']
    self.age = data['age']

saving json object in model like:

>> obj = Geek()
>> obj.jsonToModel(jsondata)
>>obj.save

now i want to update an existing model instance say , i have following json data for model instance id=1

{
"lastname": "kumar"
}


>> ob = Geek.objects.get(id=1)

now how can i do like following by not explicitly using fieldname (lastname).

>> ob.*field* = *data_for_field*  
>> ob.save()
like image 857
navyad Avatar asked Feb 15 '14 12:02

navyad


1 Answers

If you are going to be turning JSON data into models across your application it would probably be better to use one of the existing solutions for this such as the wonderful Django REST Framework. It works a lot like submitting Django forms and will provide a lot of important security and cleaning boilerplate.

If you are determined to roll your own implementation, you could use setattr(). This would allow you to set an arbitrary attribute on your model, so you could do the following:

json_data = {"lastname":"kumar"}

ob = Geek.objects.get(id=1)
for key, value in json_data.items():
   setattr(ob, key, value)
ob.save()

However, this is a bit dangerous as it would allow any arbitrary key to be set as an attribute of your object. To avoid this you could make another method on your Geek model:

def update_field(self, key, value):
     # This will raise an AttributeError if the key isn't an attribute 
     # of your model
     getattr(self, key) 
     setattr(self, key, value)

Then you could use:

json_data = {"lastname":"kumar"}

ob = Geek.objects.get(id=1)
for key, value in json_data.items():
   ob.update_field(key, value)
ob.save(update_fields=json_data.keys()) # This will only save the updated keys
like image 85
Jonathan Evans Avatar answered Sep 29 '22 07:09

Jonathan Evans