Matt S.
Matt S.

Reputation: 1159

How to set django model field by name?

This seems like it should be dead simple, so I must be missing something. I just want to set the value of a field in my model instance by name. Say I have:

class Foo(Model):
  bar = CharField()

f = Foo()

I want to set the value of bar by name, not by accessing the field. So something like:

f.fields['bar'] = 'BAR"

instead of

f.bar = 'BAR'

I've tried setattr but it doesn't persist the value in the database. I also tried going through _meta.fields but got various errors along the way.

Upvotes: 42

Views: 33471

Answers (2)

Paul McMillan
Paul McMillan

Reputation: 20107

If you modify the value via setattr, you need to remember to save the model after modifying it. I've been bitten in the past where I changed the values but forgot to save the model, and got the same result.

setattr(f, 'bar', 'BAR')
f.save()

Upvotes: 86

Joe Holloway
Joe Holloway

Reputation: 28948

We may have to see more code.

setattr(f, 'bar', 'BAR')

should work as this is how Django does it internally.

Make sure you are calling 'save', as well.

Upvotes: 22

Related Questions