[Solved]-Update model instance with dynamic field names

36👍

You can use setattr:

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

[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.

👤miku

Leave a comment