'sqlalchemy: rename a column on *query* level
I need to rename a column in a query, but I can't do it on column level, eg
session.query(MyModel.col_name.label('new_name'))
Is there any way to rename a column on the resulting query object?
Eg, something like
session.query(...).blah().blah().rename_column('old_name', 'new_name')
Solution 1:[1]
It doesn't look like there's any built in solution for that – but here's a workaround I've implemented which may help you:
To rename before the query has been executed:
# Start off with your regular query – but as a subquery
query = session.query(MyModel.col_name.label('old_name')).subquery()
# Now, perform a second query with new labels
query_2 = session.query(query.c.old_name.label('new_name'))
# Or, if there's only one column:
query_3 = session.query(query.label('new_name'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |