tags:

views:

46

answers:

1

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?

+5  A: 

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.

The MYYN
Neato, solved. thanks
herpderp