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?
The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.
The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.
Python Flask and SQLAlchemy ORM All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.
Use the label(...)
function: 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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With