- SQLAlchemy 教程
- SQLAlchemy - 主页
- SQLAlchemy - 简介
- SQLAlchemy 核心
- 表达语言
- 连接到数据库
- 创建表
- SQL 表达式
- 执行表达式
- 选择行
- 使用文本 SQL
- 使用别名
- 使用 UPDATE 表达式
- 使用 DELETE 表达式
- 使用多个表
- 使用多个表更新
- 按参数顺序更新
- 多表删除
- 使用连接
- 使用连词
- 使用函数
- 使用集合运算
- SQLAlchemy ORM
- 声明映射
- 创建会话
- 添加对象
- 使用查询
- 更新对象
- 应用过滤器
- 过滤器运算符
- 返回列表和标量
- 文本SQL
- 建立关系
- 使用相关对象
- 使用连接
- 常见关系运算符
- 急切加载
- 删除相关对象
- 多对多关系
- 方言
- SQLAlchemy 有用资源
- SQLAlchemy - 快速指南
- SQLAlchemy - 有用的资源
- SQLAlchemy - 讨论
常见关系运算符
在本章中,我们将讨论建立在关系之上的运算符。
__eq__()
上面的运算符是多对一的“等于”比较。该运算符的代码行如下所示 -
s = session.query(Customer).filter(Invoice.invno.__eq__(12))
上述代码行的等效 SQL 查询是 -
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers, invoices WHERE invoices.invno = ?
__ne__()
该运算符是多对一的“不等于”比较。该运算符的代码行如下所示 -
s = session.query(Customer).filter(Invoice.custid.__ne__(2))
上述代码行的等效 SQL 查询如下 -
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers, invoices WHERE invoices.custid != ?
包含()
该运算符用于一对多集合,下面给出的是 contains() 的代码 -
s = session.query(Invoice).filter(Invoice.invno.contains([3,4,5]))
上述代码行的等效 SQL 查询是 -
SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE (invoices.invno LIKE '%' + ? || '%')
任何()
any() 运算符用于集合,如下所示 -
s = session.query(Customer).filter(Customer.invoices.any(Invoice.invno==11))
上述代码行的等效 SQL 查询如下所示 -
SELECT customers.id AS customers_id, customers.name AS customers_name, customers.address AS customers_address, customers.email AS customers_email FROM customers WHERE EXISTS ( SELECT 1 FROM invoices WHERE customers.id = invoices.custid AND invoices.invno = ?)
有()
该运算符用于标量引用,如下所示 -
s = session.query(Invoice).filter(Invoice.customer.has(name = 'Arjun Pandit'))
上述代码行的等效 SQL 查询是 -
SELECT invoices.id AS invoices_id, invoices.custid AS invoices_custid, invoices.invno AS invoices_invno, invoices.amount AS invoices_amount FROM invoices WHERE EXISTS ( SELECT 1 FROM customers WHERE customers.id = invoices.custid AND customers.name = ?)