Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access Django model's fields using a string instead of dot syntax?

In Django, I can do this:

test = Test.objects.get(id=1) test.name 

I want to be able to access the properties using dynamically generated strings, like this:

test['name'] 

or, any other syntax using a string. I tried

test._meta.get_field_by_name('name') 

but this returns the field itself and not the value.

Any ideas?

like image 940
davidscolgan Avatar asked Feb 21 '12 14:02

davidscolgan


People also ask

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.

What is text field in Django models?

TextField is a large text field for large-sized text. TextField is generally used for storing paragraphs and all other text data. The default form widget for this field is TextArea.

Is there a list field for Django models?

Mine is simpler to implement, and you can pass a list, dict, or anything that can be converted into json. In Django 1.10 and above, there's a new ArrayField field you can use.

How do I add a model field in Django?

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.


1 Answers

You can use python's built in getattr() function:

getattr(test, 'name') 
like image 95
Caspar Avatar answered Oct 06 '22 15:10

Caspar