Reputation: 29081
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')
Upvotes: 6
Views: 4942
Reputation: 60875
I've figured out a way to do this. In my case, I was having issues with except_
, which prefixes columns with the table name. Here's how I did that:
def _except(included_query, excluded_query, Model, prefix):
"""An SQLALchemy except_ that removes the prefixes on the columns, so they can be
referenced in a subquery by their un-prefixed names."""
query = included_query.except_(excluded_query)
subquery = query.subquery()
# Get a list of columns from the subquery, relabeled with the simple column name.
columns = []
for column_name in _attribute_names(Model):
column = getattr(subquery.c, prefix + column_name)
columns.append(column.label(column_name))
# Wrap the query to select the simple column names. This is necessary because
# except_ prefixes column names with a string derived from the table name.
return Model.query.from_statement(Model.query.with_entities(*columns).statement)
Upvotes: 0
Reputation: 12018
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'))
Upvotes: 2