94

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?

davidscolgan
  • 7,508
  • 9
  • 59
  • 78

4 Answers4

137

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

getattr(test, 'name')
Caspar
  • 7,039
  • 4
  • 29
  • 41
17

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

arie
  • 18,737
  • 5
  • 70
  • 76
15

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.

davidhwang
  • 1,343
  • 1
  • 12
  • 19
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
James R
  • 4,571
  • 3
  • 30
  • 45
  • 1
    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. – Chris Pratt Feb 21 '12 at 15:42
  • @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. http://docs.python.org/reference/datamodel.html#specialnames http://www.siafoo.net/article/57 http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python – ashwoods Feb 22 '12 at 07:51
  • 1
    @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. – Chris Pratt Feb 22 '12 at 15:17
  • @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. – James R Feb 22 '12 at 15:34