Reputation: 46909
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
Upvotes: 2
Views: 3516
Reputation: 40755
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.
Upvotes: 8
Reputation: 15962
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'
Upvotes: 1