Select as in sqlalchemy

I want to do something like this:

select username, userid, 'user' as new_column  from  users_table.

The columns of the table can be selected using sqlalchemy as follows:

query = select([users_table.c.username, users_table.c.userid])

How do I do the select x as col_x to the query in sqlalchemy?

Answers


use this: users_table.c.userid.label('NewColumn')

i.e.,

query = select([users_table.c.username, users_table.c.userid.label('NewColumn')])

evaluates to:

SELECT username , userid as NewColumn From MyTable;

Maybe literal_column?

query = select([users_table.c.username, users_table.c.userid, literal_column("user", type_=Unicode).label('new_column')])

See http://www.sqlalchemy.org/docs/reference/sqlalchemy/expressions.html#sqlalchemy.sql.expression.literal_column

Edit: actually I should have said "literal":

query = select([users_table.c.username, users_table.c.userid, literal("user", type_=Unicode).label('new_column')])

See the alias() in here: http://www.sqlalchemy.org/docs/05/reference/sqlalchemy/expressions.html


Need Your Help

Does dependency injection exist in Rails?

ruby-on-rails ruby spring dependency-injection

Does the fact that Rails have an MVC approach mean that is has dependency injection?

Nested types inside a protocol

swift protocols swift-protocols

It is possible to have nested types declared inside protocols, like this: