What I want to do is pretty simple:
f=Foobar.objects.get(id=1)
foo='somefield'
bar='somevalue'
f.foo=bar
f.save()
This doesn't work as it tries to update the f object's 'foo' field, which of course doesn't exist. How can I accomplish this?
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 ofgetattr()
. 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.
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