Whoami
Whoami

Reputation: 14418

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?

Upvotes: 5

Views: 4167

Answers (2)

Victor Castillo Torres
Victor Castillo Torres

Reputation: 10811

try:

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

Here is the doc

Upvotes: 2

sgarza62
sgarza62

Reputation: 6238

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.

Upvotes: 10

Related Questions