Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update model instance with dynamic field names

Tags:

python

django

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?

like image 753
herpderp Avatar asked May 30 '10 05:05

herpderp


1 Answers

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.

like image 165
miku Avatar answered Oct 09 '22 01:10

miku