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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With