Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 698
Matt S. Avatar asked Oct 09 '09 19:10

Matt S.


People also ask

How do you define a name field in a Django model?

¶ 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.

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How do I add a field to a Django 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.

How do you define choice fields in Django?

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.


2 Answers

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() 
like image 63
Paul McMillan Avatar answered Sep 20 '22 17:09

Paul McMillan


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.

like image 27
Joe Holloway Avatar answered Sep 17 '22 17:09

Joe Holloway