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.
¶ Naming of a column in the model can be achieved py passing a db_column parameter with some name. If we don't pass this parameter django creates a column with the field name which we give.
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
To answer your question, with the new migration introduced in Django 1.7, in order to add a new field to a model you can simply add that field to your model and initialize migrations with ./manage.py makemigrations and then run ./manage.py migrate and the new field will be added to your DB. Save this answer.
Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only.
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()
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.
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