99

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?

4 Answers 4

145

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

getattr(test, 'name')
Sign up to request clarification or add additional context in comments.

5 Comments

A minute too slow! Shouldn't have taken the time to test it out ;)
Ah, I didn't even have to use Django functionality, and I learned something new about Python. Thanks for the help.
Works for ForeignKey?
Would anyone know how we call this within an internal class method for said Model.... self.getattr(SelfModelName, 'id') = ??
A bit late, but you can just use getattr(self, 'id')
18

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: The Python getattr Function

Comments

14

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.

1 Comment

This still returns the field itself, and the OP was interested in the field's value.
6

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

4 Comments

It'll work, but generally, you want to avoid using underscored attributes/methods if at all possible. It's a signal that they're volatile (open to being completely dropped or inherently changed at any time, with no warning) or not intended to be part of the public interface for some other reason. Sometimes you have to, but in this case, getattr is available and is the right choice, as a result.
@ChrisPratt There is a difference between single underscore, double underscore, and double underscore with trailing double underscore. While what you said applies (more or less) to the former two, the method implies that it is a builtin, and is no indication of privacy or protection whatsoever, and its where you normally do operator overloading and initialization. docs.python.org/reference/datamodel.html#specialnames siafoo.net/article/57 stackoverflow.com/questions/1301346/…
@ashwoods: true, but even then, the use of them is generally contained inside another class, so it's sort of an internal code using internal code situation. Ultimately, you generally don't use such methods out in the wild only in other classes that still tuck the specific implementation away from the "public" interface.
@ChrisPratt, this is all rather academic at this point, but if you refer to page 84 of Python in a Nutshell, second edition he describes this behavior. He says, "There is no difference between class attributes created in the class body, outside the body by assigning an attribute, or outside the body by explicitly binding an entry in C.__dict__. That said, I agree that getattr is probably the right solution in this circumstance, but that doesn't mean one can't use the dict internal outside of the class body, or any other double underscore method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.