SQLAlchemy 中的链式比较 [英] Chained comparisons in SQLAlchemy

查看:23
本文介绍了SQLAlchemy 中的链式比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 支持链式比较:1 <2<3 转换为 (1 <2) 和 (2 <3).

Python supports chained comparisons: 1 < 2 < 3 translates to (1 < 2) and (2 < 3).

我正在尝试使用 SQLAlchemy 进行 SQL 查询,如下所示:

I am trying to make an SQL query using SQLAlchemy which looks like this:

results = session.query(Couple).filter(10 < Couple.NumOfResults < 20).all()

我得到的结果并不像预期的那样.我已经打开了引擎的 echo=True 关键字,并且确实 - 生成的 SQL 查询仅包含两个比较之一.

The results I got were not as expected. I've turned the engine's echo=True keyword, and indeed - the generated SQL query only included one of the two comparisons.

我找不到任何明确说明这是禁止的文件.我假设如果 Python 支持这种类型的表达式,那么 SQLAlchemy 也应该支持它.

I can't find any documentation that explicitly says this is forbidden. I assumed that if this type of expression is supported in Python, it should be supported in SQLAlchemy as well.

为什么这不起作用?我有一个可能的解决方案(在答案中分享),但很高兴听到其他意见.

Why doesn't this work? I have one possible solution in mind (shared in answers), but will be glad to hear other opinions.

推荐答案

原因是 Python 实际上会评估类似这样的东西:

The reason is that Python actually evaluates something akin to this:

_tmp = Couple.NumOfResults
(10 < _tmp and _tmp < 20)

and 运算符在 SQLAlchemy 中不受支持(应该使用 and_ 代替).因此 - SQLAlchemy 中不允许进行链式比较.

The and operator is unsupported in SQLAlchemy (one should use and_ instead). And thus - chained comparisons are not allowed in SQLAlchemy.

在原来的例子中,你应该写这个代码:

In the original example, one should write this code instead:

results = session.query(Couple).filter(and_(10 < Couple.NumOfResults, 
                                            Couple.NumOfResults < 20)).all()

这篇关于SQLAlchemy 中的链式比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆