0

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

1 Answer 1

1

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] 
Sign up to request clarification or add additional context in comments.

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.