Update model instance with dynamic field names

What I want to do is pretty simple:

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

This does not work as it tries to update the ff 'foo field, which of course does not exist. How can i do this?

+4
source share
1 answer

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 an analogue of getattr() . The arguments are an object, a string, and an arbitrary value. A string can name an existing attribute or a new attribute. The function assigns a value to the attribute if the object allows it.

+14
source

Source: https://habr.com/ru/post/1311331/


All Articles