Reputation: 31951
How can I get at the column of a result if I have a variable for the column? The below is a simplified example. I have a variable that contains the column I want, which will be used in the query. I now want to get the same column from the result.
col_id = some_table.id
query = session.query(col_id)
for row in query:
id = row ?? col_id
I don't want to have to know the name of the column, as the actual code structure is more like this:
col_id, query = build_query()
for row in query:
id = row ?? col_id
Upvotes: 0
Views: 710
Reputation: 55943
You can access it using the key
attribute of the column.
for row in query:
id_ = row[col_id.key]
but this approach is deprecated and will be removed in SQLAlchemy 2.0. The recommended approach is to use the row's _mapping
attribute.
for row in query:
id_ = row._mapping[id_col.key]
or you could output the rows as dictionaries:
for row in query.mappings():
id_ = row[id_col.key]
Upvotes: 1