tags:

views:

49

answers:

2

Hi,

I have a list of fields for an object:

fields = ('title', 'first_name', 'last_name)

Now I want to access the fields of my object on runtime, without harcoding it like this.

myobject.title

What I'm searching for is something like this:

myobject.getFieldValue('title')

Is there a method like this in django? I did not find one.

+4  A: 

Not a Django method, but a standard Python builtin:

getattr(myobject, 'title')
Daniel Roseman
Thanks! That works!
Tom Tom
A: 

But if you can access the attribute of a object by something like this myobject.title, why do you want a manager (in case of a database query) or a function to do this?

Prashanth
I think there are some use-cases where you want to access the value of a field without hardprinting it. My use-case is the following: I have a view that presents all Contacts in a table. This table is created based on a list, called: HEADERS_CONTACT. I'm using this list in different views and functions. One function is export contacts. Here I want to export the same values as defined in HEADERS_CONTACT. Thus if I decide to present more details of a contact in the contact overview I will change the HEADERS_CONTACT list and can be sure that my export function will export the values accordingly.
Tom Tom
We have some MixIn classes we use across a large number of database models. Most *but not all* of them have a particular field (e.g. `title`) so in the methods of the MixIn class we have to use hasattr() to make sure it will work, and then getattr(), normally with a default value supplied.
Peter Rowell