2

In the following code data_var is my object from a Django query, i.e. data_var = Datavar.objects.all(). I have database fields like field1, field2, field3, etc. In the following code I am trying to get the name of the field as a string in var and then say tg.var but I get an error as object has no attribute 'var':

If I say tg.var it should be interpreted as tg.field1 or 2 or 3. How to achieve this?

for tg in data_var:
     for col in range(content.no_of_cols):
        var = "field" + str(col)
        tg.var 
2
  • Can you clarify what your expected output should be? An example would be nice. Commented Aug 9, 2012 at 12:12
  • i have hight lighted it.tg.var should be assumed as tg.field1 etc.... Commented Aug 9, 2012 at 12:13

2 Answers 2

8

To get object's attribute with a string name you should use getattr built-in function, and that way transforms your code to the next lines:

for tg in data_var:
     for col in range(content.no_of_cols):
        var = "field" + str(col)
        value = getattr(tg, var)

gettatr is explained in Python doc.

Sign up to request clarification or add additional context in comments.

Comments

1

Looks like you're trying variable variables like in PHP. Python doesn't have it. You need to use a dictionary or getattr.

(Edit-ing since the first answer already covers getattr).

You can also refer to it from the dict:

>>> var = 'field1'
>>> tg.__dict__[var]
'this is field1'
>>> var = 'field2'
>>> tg.__dict__[var]
'this is field2'
>>> getattr(tg, var)
'this is field2'

Comments

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.