python sqlalchemy 标签用法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15555920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:23:19  来源:igfitidea点击:

python sqlalchemy label usage

pythonsqlalchemyalias

提问by Ofir

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:

我知道我可以使用 label 方法作为别名,但我无法弄清楚如何在查询中稍后使用带标签的元素 - 类似于以下内容:

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?

当然,这不起作用,因为没有名为 foobar 的变量。这怎么可能实现?

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

(过度简化的例子只是为了便于理解......)

采纳答案by Eevee

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

回答by alecxe

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

只需将 foobar 放在引号中。它会order_by像这样工作:

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

For filter you can use raw sql conditions:

对于过滤器,您可以使用原始 sql 条件:

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