Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update existing model instance from dictionary value

Given the model instance, for example StackOverflow is the model, and

 obj = StackOverflow.objects.get(..somecondition)
 dict  = { 'rating' : 3, 'field1' : 'question', field2 : 'answer' }

StackOverflow model has all the keys that are available int the dict as a member variable.

I want to update obj with dict values.

How can i achieve the same?

like image 455
Whoami Avatar asked Dec 25 '22 18:12

Whoami


1 Answers

obj = StackOverflow.objects.get(pk=1)
d  = { 'rating' : 3, 'field1' : 'question', 'field2' : 'answer' }

for i in d:
    setattr(obj, i, d[i])
obj.save()

This will work, assuming the dictionary keys correspond to fields in the StackOverflow model, and the dictionary values are valid field values.

like image 197
sgarza62 Avatar answered Dec 28 '22 08:12

sgarza62