SQLAlchemy中的链接比较 [英] Chained comparisons in 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 probably that Python actually evaluates this expression:
(10< Couple.NumOfResults and Couple.NumOfResults< 20 )
SQLAlchemy不支持和
运算符$ c>和_ )。因此,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屋!