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

DjangoDjango Models

Django Problem Overview


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?

Django Solutions


Solution 1 - Django

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

getattr(test, 'name')

Solution 2 - Django

Assuming name is an attribute on your instance test getattr(test, 'name') should return the corresponding value. Or test.__dict__['name'].

You can read more about getattr() here: http://effbot.org/zone/python-getattr.htm

Solution 3 - Django

Other answers still stand, but now you can do this using Django's _meta.get_field().

test._meta.get_field('name')

Note that the Model _meta API has begun its official support and documentation as of 1.8, but has been distributed and used in prior versions before its official documentation.

Solution 4 - Django

In Python, you can normally access values within an object that has a dict method.

Let's say you have this class:

class Dog(object):
    def __init___(self, color):
        self.color = color

And then I instantiate it:

dog = Dog('brown')

So i can see the color by doing:

print dog.color

I can also see the color by doing:

print dog.__dict__['color']

I can set the color:

print dog.__dict__['color'] = 'green'

print dog.color

>>>green

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondavidscolganView Question on Stackoverflow
Solution 1 - DjangoCasparView Answer on Stackoverflow
Solution 2 - DjangoarieView Answer on Stackoverflow
Solution 3 - DjangodavidhwangView Answer on Stackoverflow
Solution 4 - DjangoJames RView Answer on Stackoverflow