Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sqlalchemy label usage

I know I can use the label method for alias, but I can't figure out how to use the labeled element later in the query - something like the following:

session.query(Foo.bar.label("foobar")).filter(foobar > 10).all() 

Of course, this doesn't work since there is no variable called foobar. How could this be accomplished?

(The over simplified example was just for easy comprehension...)

like image 228
Ofir Avatar asked Mar 21 '13 18:03

Ofir


People also ask

What is label in SQLAlchemy?

Label is a class within the sqlalchemy. sql. elements module of the SQLAlchemy project. ColumnElement is another callable from the sqlalchemy.

Is SQLAlchemy worth using?

SQLAlchemy is the ORM of choice for working with relational databases in python. The reason why SQLAlchemy is so popular is because it is very simple to implement, helps you develop your code quicker and doesn't require knowledge of SQL to get started.

What does SQLAlchemy text do?

SQLAlchemy lets you just use strings, for those cases when the SQL is already known and there isn't a strong need for the statement to support dynamic features. The text() construct is used to compose a textual statement that is passed to the database mostly unchanged.

Do companies use SQLAlchemy?

Who uses SQLAlchemy? 90 companies reportedly use SQLAlchemy in their tech stacks, including yogiyo, Hivestack, and Buzzvil.


2 Answers

Offhand, I believe you can use the labeled column itself as an expression:

foobar = Foo.bar.label("foobar") session.query(foobar).filter(foobar > 10).all() 
like image 69
Eevee Avatar answered Sep 20 '22 11:09

Eevee


Just put foobar in quotes. It'll work for order_by like this:

session.query(Foo.bar.label("foobar")).order_by('foobar').all() 

For filter you can use raw sql conditions:

session.query(Foo.bar.label("foobar")).filter("foobar > 10").all() 
like image 22
alecxe Avatar answered Sep 17 '22 11:09

alecxe