Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 656
user401574 Avatar asked Aug 26 '10 14:08

user401574


People also ask

How do I select 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.

What is subquery 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.

How does the querying work with SQLAlchemy?

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.


1 Answers

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; 
like image 157
pylover Avatar answered Sep 28 '22 02:09

pylover