gpt4 book ai didi

python - sqlalchemy 查询方法如何工作?

转载 作者:太空宇宙 更新时间:2023-11-03 15:20:35 24 4
gpt4 key购买 nike

我正在学习 sqlachemy,我对 Python 比较陌生。

当我阅读它的文档时,我看到了 this kind of usage ,例如:

query.filter(User.name == 'ed')

Python 不会计算表达式 User.name == 'ed' 然后将结果( bool 值)传递给 query.filter 方法吗?

这种语法是如何工作的? Python 是否像 C++ 一样支持某种运算符覆盖?

最佳答案

SQLAlchemy 使用各种 special method hooks重载运算符行为。

对于 ==__eq__() 方法在编译时返回表示 SQL 表达式的特殊对象。引用有关“丰富比较” Hook 的文档:

By convention, False and True 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 an if statement), Python will call bool() on the value to determine if the result is true or false.

参见 ColumnOperators class在 SQLAlchemy 源代码中实现了特定的 Hook 。

关于python - sqlalchemy 查询方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15701804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com