python sqlalchemy label usage

ぃ、小莉子 提交于 2019-12-17 16:15:41

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/15555920/python-sqlalchemy-label-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!