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...)
Label is a class within the sqlalchemy. sql. elements module of the SQLAlchemy project. ColumnElement is another callable from the sqlalchemy.
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.
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.
Who uses SQLAlchemy? 90 companies reportedly use SQLAlchemy in their tech stacks, including yogiyo, Hivestack, and Buzzvil.
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()
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()
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