sqlachemy 查询方法如何工作? [英] How does sqlachemy query method work?
问题描述
我正在学习 sqlachemy,我对 Python 比较陌生.
I am learning sqlachemy, I'm relatively new to Python.
当我阅读它的文档时,我看到了这种用法,例如:
When I read its documentation, I saw this kind of usage, for example:
query.filter(User.name == 'ed')
query.filter(User.name == 'ed')
Python 不会评估表达式 User.name == 'ed'
然后将结果(布尔值)传递给 query.filter
方法吗?
Wouldn't Python evaluate the expression User.name == 'ed'
and then pass the result, which is a boolean, to query.filter
method?
这种语法是如何工作的?Python 是否支持某种运算符覆盖,例如 C++?
How does this kind of syntax work? Does Python support some kind of operator overriding like C++?
推荐答案
SQLAlchemy 使用各种 特殊方法钩子 用于重载运算符行为.
SQLAlchemy uses the various special method hooks to overload operator behaviour.
对于 ==
,__eq__()
方法在编译时返回表示 SQL 表达式的特殊对象.引用有关丰富比较"挂钩的文档:
For ==
, the __eq__()
method returns special objects that signify a SQL expression when compiled. To quote the documentation on the 'rich comparison' hooks:
按照惯例,False
和 True
会返回以进行成功的比较.但是,这些方法可以返回任何值,因此如果在布尔上下文中使用比较运算符(例如,在 if
语句的条件中),Python 将调用 bool()
上的值来确定结果是真还是假.
By convention,
False
andTrue
are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of anif
statement), Python will callbool()
on the value to determine if the result is true or false.
参见ColumnOperators
class 在 SQLAlchemy 源代码中用于实现的特定钩子.
See the ColumnOperators
class in the SQLAlchemy source for the specific hooks implemented.
这篇关于sqlachemy 查询方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!