42

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

Ofir
  • 1,565
  • 3
  • 23
  • 41

4 Answers4

59

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()
Eevee
  • 47,412
  • 11
  • 95
  • 127
31

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()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2
# 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"))
0

Wanted to add on to @Eevee's answer:

This can also work similarly for func.coalesce() calls. You can assign the result of func.coalesce() to a variable, then reference that variable in a filter. For example:

x = func.coalesce(Order.x, Order.y)
y = query(<model>).filter(x = 10)
Klutch27
  • 167
  • 2
  • 9