[Solved]-Update model instance with dynamic field names


You can use setattr:

f = Foobar.objects.get(id=1)
foo = 'somefield'
bar = 'somevalue'
setattr(f, foo, bar) # f.foo=bar

[setattr] is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.


Leave a comment