Django: how to update model field from json data

I have json data like:

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

I have defined a custom method for the Geek model to save it from a 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 the model, for example:

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

now I want to update an existing model instance let's say I have the following json data for the model instance id = 1

{
"lastname": "kumar"
}


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

now how can i do the following without explicitly using the field name (lastname).

>> ob.*field* = *data_for_field*  
>> ob.save()
+4
source share
1 answer

JSON , , , , Django REST Framework. Django .

, setattr(). , :

json_data = {"lastname":"kumar"}

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

, . , Geek:

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)

:

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
+9
source

Source: https://habr.com/ru/post/1527083/


All Articles