python sqlalchemy label usage

Question:

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…)

Asked By: Ofir

||

Answers:

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()
Answered By: alecxe

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()
Answered By: Eevee
# When you use the SQLAlchemy Core interface you may apply text()
from sqlalchemy import text
stmt = select(Foo.c.bar.label("foobar"))
stmt = stmt.where(text("foobar > 10"))
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.