Andrei Stalbe
Andrei Stalbe

Reputation: 1531

How to retrieve model column value dynamically in python

Suppose I have a model object.

print (dir(table))
['...', 'col1', 'col2', '...']

# this will output column 1 value
print (table.col1)

I would like to do it dynamically, for example:

col = 'col1'
table.col

Thx

Upvotes: 2

Views: 1080

Answers (2)

alko
alko

Reputation: 48297

To get attribute value by name use getattr

getattr(table, 'col1')

Upvotes: 2

John Spong
John Spong

Reputation: 1381

You want to use getattr when doing dynamic attribute retrieval in python:

col = 'col1'
getattr(table, col)

Upvotes: 3

Related Questions