SqlAlchemy 2.0 中文文档(二十九)(3)https://developer.aliyun.com/article/1560466
级联标量删除
版本 1.3 中的新增功能。
给定一个映射如下:
from __future__ import annotations from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.associationproxy import association_proxy, AssociationProxy from sqlalchemy.orm import DeclarativeBase, relationship from sqlalchemy.orm.collections import attribute_keyed_dict from sqlalchemy.orm.collections import Mapped class Base(DeclarativeBase): pass class A(Base): __tablename__ = "test_a" id: Mapped[int] = mapped_column(primary_key=True) ab: Mapped[AB] = relationship(uselist=False) b: AssociationProxy[B] = association_proxy( "ab", "b", creator=lambda b: AB(b=b), cascade_scalar_deletes=True ) class B(Base): __tablename__ = "test_b" id: Mapped[int] = mapped_column(primary_key=True) class AB(Base): __tablename__ = "test_ab" a_id: Mapped[int] = mapped_column(ForeignKey(A.id), primary_key=True) b_id: Mapped[int] = mapped_column(ForeignKey(B.id), primary_key=True) b: Mapped[B] = relationship()
对 A.b 的赋值将生成一个 AB 对象:
a.b = B()
A.b 关联是标量的,并包括使用参数 AssociationProxy.cascade_scalar_deletes。当启用此参数时,将A.b设置为 None 将同时删除 A.ab:
a.b = None assert a.ab is None
当 AssociationProxy.cascade_scalar_deletes 未设置时,上述关联对象 a.ab 会保持不变。
请注意,这不是基于集合的关联代理的行为;在这种情况下,当代理集合的成员被移除时,中介关联对象始终会被移除。行是否被删除取决于关联级联设置。
另请参阅
级联
标量关系
下面的示例说明了在一对多关系的多方上使用关联代理,以访问标量对象的属性:
from __future__ import annotations from typing import List from sqlalchemy import ForeignKey from sqlalchemy import String from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.ext.associationproxy import AssociationProxy from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship class Base(DeclarativeBase): pass class Recipe(Base): __tablename__ = "recipe" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] = mapped_column(String(64)) steps: Mapped[List[Step]] = relationship(back_populates="recipe") step_descriptions: AssociationProxy[List[str]] = association_proxy( "steps", "description" ) class Step(Base): __tablename__ = "step" id: Mapped[int] = mapped_column(primary_key=True) description: Mapped[str] recipe_id: Mapped[int] = mapped_column(ForeignKey("recipe.id")) recipe: Mapped[Recipe] = relationship(back_populates="steps") recipe_name: AssociationProxy[str] = association_proxy("recipe", "name") def __init__(self, description: str) -> None: self.description = description my_snack = Recipe( name="afternoon snack", step_descriptions=[ "slice bread", "spread peanut butted", "eat sandwich", ], )
使用以下命令可打印 my_snack 的摘要步骤:
>>> for i, step in enumerate(my_snack.steps, 1): ... print(f"Step {i} of {step.recipe_name!r}: {step.description}") Step 1 of 'afternoon snack': slice bread Step 2 of 'afternoon snack': spread peanut butted Step 3 of 'afternoon snack': eat sandwich
API 文档
| 对象名称 | 描述 |
| association_proxy(target_collection, attr, *, [creator, getset_factory, proxy_factory, proxy_bulk_set, info, cascade_scalar_deletes, create_on_none_assignment, init, repr, default, default_factory, compare, kw_only]) | 返回一个实现视图的 Python 属性,该视图引用目标的成员上的属性。 |
| AssociationProxy | 一个描述符,提供对象属性的读/写视图。 |
| AssociationProxyExtensionType | 一个枚举类型。 |
| AssociationProxyInstance | 一个每个类的对象,用于提供类和对象特定的结果。 |
| ColumnAssociationProxyInstance | 一个 AssociationProxyInstance,其目标为数据库列。 |
| ObjectAssociationProxyInstance | 一个 AssociationProxyInstance,其目标为对象。 |
function sqlalchemy.ext.associationproxy.association_proxy(target_collection: str, attr: str, *, creator: _CreatorProtocol | None = None, getset_factory: _GetSetFactoryProtocol | None = None, proxy_factory: _ProxyFactoryProtocol | None = None, proxy_bulk_set: _ProxyBulkSetProtocol | None = None, info: _InfoType | None = None, cascade_scalar_deletes: bool = False, create_on_none_assignment: bool = False, init: _NoArg | bool = _NoArg.NO_ARG, repr: _NoArg | bool = _NoArg.NO_ARG, default: Any | None = _NoArg.NO_ARG, default_factory: _NoArg | Callable[[], _T] = _NoArg.NO_ARG, compare: _NoArg | bool = _NoArg.NO_ARG, kw_only: _NoArg | bool = _NoArg.NO_ARG) → AssociationProxy[Any]
返回一个实现视图的 Python 属性,该视图引用目标的成员上的属性。
返回的值是 AssociationProxy 的一个实例。
实现一个代表关系的 Python 属性,作为一组更简单值的集合,或一个标量值。代理属性将模仿目标的集合类型(list、dict 或 set),或者在一对一关系的情况下,一个简单的标量值。
参数:
target_collection– 目标属性的名称。该属性通常由relationship()映射,以链接到目标集合,但也可以是一对多或非标量关系。attr– 关联实例上可用于目标对象实例的属性。creator–
可选。
定义了向代理集合添加新项时的自定义行为。
默认情况下,向集合添加新项将触发构造目标对象的实例,将给定项作为位置参数传递给目标构造函数。对于这种情况不足的情况,association_proxy.creator可以提供一个可调用对象,该对象将以适当的方式构造对象,给定传递的项。
对于列表和集合导向的集合,将一个参数传递给可调用对象。对于字典导向的集合,将传递两个参数,对应于键和值。association_proxy.creator可调用对象也会为标量(即一对多,一对一)关系调用。如果目标关系属性的当前值为None,则使用可调用对象构造一个新对象。如果对象值已经存在,则给定的属性值将填充到该对象上。
另请参见
创建新值cascade_scalar_deletes–
当为 True 时,表示将代理值设置为None,或通过del删除时,也应该删除源对象。仅适用于标量属性。通常,删除代理目标不会删除代理源,因为该对象可能还有其他状态需要保留。
新版本 1.3 中新增。
另请参见
级联标量删除 - 完整的使用示例create_on_none_assignment–
当为 True 时,表示将代理值设置为None应该创建源对象(如果不存在),使用创建者。仅适用于标量属性。这与assocation_proxy.cascade_scalar_deletes是互斥的。
新版本 2.0.18 中新增。init–
特定于声明性数据类映射,指定映射属性是否应该是由数据类过程生成的__init__()方法的一部分。
新版本 2.0.0b4 中新增。repr–
特定于 声明性数据类映射,指定由此AssociationProxy建立的属性是否应作为数据类过程生成的__repr__()方法的一部分。
新功能,版本为 2.0.0b4。default_factory–
特定于 声明性数据类映射,指定作为数据类过程的一部分进行的默认值生成函数。
新功能,版本为 2.0.0b4。compare–
特定于 声明性数据类映射,指示在为映射类生成__eq__()和__ne__()方法时,是否应将此字段包括在比较操作中。
新功能,版本为 2.0.0b4。kw_only–
特定于 声明性数据类映射,指示在为数据类过程生成的__init__()方法中,是否应将此字段标记为仅关键字。
新功能,版本为 2.0.0b4。info– 可选项,如果存在,将分配给AssociationProxy.info。
下列附加参数涉及在 AssociationProxy 对象中注入自定义行为,仅供高级使用:
参数:
getset_factory–
可选项。代理属性访问由基于该代理的 attr 参数的 get 和 set 值的例程自动处理。
如果您想自定义此行为,可以提供一个 getset_factory 可调用对象,该对象会生成一个 getter 和 setter 函数的元组。工厂使用两个参数调用,即底层集合的抽象类型和此代理实例。proxy_factory– 可选项。要模拟的集合类型由嗅探目标集合确定。如果无法通过鸭子类型确定您的集合类型,或者您想使用不同的集合实现,可以提供一个工厂函数来生成这些集合。仅适用于非标量关系。proxy_bulk_set– 可选项,与 proxy_factory 一起使用。
class sqlalchemy.ext.associationproxy.AssociationProxy
描述符,用于呈现对象属性的读/写视图。
成员
init(), cascade_scalar_deletes, create_on_none_assignment, creator, extension_type, for_class(), getset_factory, info, is_aliased_class, is_attribute, is_bundle, is_clause_element, is_instance, is_mapper, is_property, is_selectable, key, proxy_bulk_set, proxy_factory, target_collection, value_attr
类签名
类sqlalchemy.ext.associationproxy.AssociationProxy (sqlalchemy.orm.base.InspectionAttrInfo, sqlalchemy.orm.base.ORMDescriptor, sqlalchemy.orm._DCAttributeOptions, sqlalchemy.ext.associationproxy._AssociationProxyProtocol)
method __init__(target_collection: str, attr: str, *, creator: _CreatorProtocol | None = None, getset_factory: _GetSetFactoryProtocol | None = None, proxy_factory: _ProxyFactoryProtocol | None = None, proxy_bulk_set: _ProxyBulkSetProtocol | None = None, info: _InfoType | None = None, cascade_scalar_deletes: bool = False, create_on_none_assignment: bool = False, attribute_options: _AttributeOptions | None = None)
构造一个新的AssociationProxy。
AssociationProxy对象通常使用association_proxy()构造函数构造。有关所有参数的描述,请参阅association_proxy()的描述。
attribute cascade_scalar_deletes: bool
attribute create_on_none_assignment: bool
attribute creator: _CreatorProtocol | None
attribute extension_type: InspectionAttrExtensionType = 'ASSOCIATION_PROXY'
扩展类型,如果有的话。默认为NotExtension.NOT_EXTENSION
另请参阅
HybridExtensionType
AssociationProxyExtensionType
method for_class(class_: Type[Any], obj: object | None = None) → AssociationProxyInstance[_T]
返回特定映射类的内部状态。
例如,给定一个类 User:
class User(Base): # ... keywords = association_proxy('kws', 'keyword')
如果我们从 Mapper.all_orm_descriptors 访问此 AssociationProxy,并且我们想要查看由 User 映射的此代理的目标类:
inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class
这将返回一个特定于 User 类的 AssociationProxyInstance 实例。 AssociationProxy 对象保持对其父类的不可知性。
参数:
class_– 我们要返回状态的类。obj– 可选,如果属性引用多态目标,则需要该类的实例,例如,在我们必须查看实际目标对象的类型以获取完整路径的情况下。
版本 1.3 中的新功能:- AssociationProxy 不再存储任何特定于特定父类的状态;状态现在存储在每个类的 AssociationProxyInstance 对象中。
attribute getset_factory: _GetSetFactoryProtocol | None
attribute info
从 InspectionAttrInfo 的 InspectionAttrInfo.info 属性继承
与该 InspectionAttr 关联的信息字典,允许将用户定义的数据与此对象关联。
字典在首次访问时生成。或者,它可以作为 column_property()、relationship() 或 composite() 函数的构造函数参数指定。
另请参阅
QueryableAttribute.info
SchemaItem.info
attribute is_aliased_class = False
从 InspectionAttr 的 InspectionAttr.is_aliased_class 属性继承
如果此对象是 AliasedClass 的实例,则为 True。
attribute is_attribute = True
如果此对象是 Python 的 descriptor 则为 True。
这可以指代多种类型。通常是一个 QueryableAttribute,它代表一个 MapperProperty 处理属性事件。但也可以是一个扩展类型,如 AssociationProxy 或 hybrid_property。InspectionAttr.extension_type 将指代一个特定子类型的常量。
另请参阅
Mapper.all_orm_descriptors
attribute is_bundle = False
继承自 InspectionAttr 的 InspectionAttr.is_bundle *属性。
如果此对象是 Bundle 的实例,则为 True。
attribute is_clause_element = False
继承自 InspectionAttr 的 InspectionAttr.is_clause_element *属性。
如果此对象是 ClauseElement 的实例,则为 True。
attribute is_instance = False
继承自 InspectionAttr 的 InspectionAttr.is_instance *属性。
如果此对象是 InstanceState 的实例,则为 True。
attribute is_mapper = False
继承自 InspectionAttr 的 InspectionAttr.is_mapper *属性。
如果此对象是 Mapper 的实例,则为 True。
attribute is_property = False
继承自 InspectionAttr 的 InspectionAttr.is_property *属性。
如果此对象是 MapperProperty 的实例,则为 True。
attribute is_selectable = False
继承自 InspectionAttr 的 InspectionAttr.is_selectable *属性。
如果此对象是Selectable的实例,则返回 True。
attribute key: str
attribute proxy_bulk_set: _ProxyBulkSetProtocol | None
attribute proxy_factory: _ProxyFactoryProtocol | None
attribute target_collection: str
attribute value_attr: str
class sqlalchemy.ext.associationproxy.AssociationProxyInstance
一个为类和对象提供特定结果的对象。
当AssociationProxy在特定类或类实例的术语中被调用时,即当它被用作常规的 Python 描述符时,会使用这个对象。
当将AssociationProxy作为普通的 Python 描述符引用时,AssociationProxyInstance是实际提供信息的对象。在正常情况下,它的存在是透明的:
>>> User.keywords.scalar False
在特殊情况下,直接访问AssociationProxy对象时,为了获得对AssociationProxyInstance的明确处理,使用AssociationProxy.for_class()方法:
proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User) # view if proxy object is scalar or not >>> proxy_state.scalar False
版本 1.3 中的新功能。
成员
eq(), le(), lt(), ne(), all_(), any(), any_(), asc(), attr, between(), bitwise_and(), bitwise_lshift(), bitwise_not(), bitwise_or(), bitwise_rshift(), bitwise_xor(), bool_op(), collate(), collection_class, concat(), contains(), delete(), desc(), distinct(), endswith(), for_proxy(), get(), has(), icontains(), iendswith(), ilike(), in_(), info, is_(), is_distinct_from(), is_not(), is_not_distinct_from(), isnot(), isnot_distinct_from(), istartswith(), like(), local_attr, match(), not_ilike(), not_in(), not_like(), notilike(), notin_(), notlike(), nulls_first(), nulls_last(), nullsfirst(), nullslast(), op(), operate(), parent, regexp_match(), regexp_replace(), remote_attr, reverse_operate(), scalar, set(), startswith(), target_class, timetuple
类签名
类sqlalchemy.ext.associationproxy.AssociationProxyInstance (sqlalchemy.orm.base.SQLORMOperations)
method __eq__(other: Any) → ColumnOperators
继承自 sqlalchemy.sql.expression.ColumnOperators.__eq__ 方法的 ColumnOperators 方法
实现==运算符。
在列上下文中,生成子句a = b。如果目标是None,则生成a IS NULL。
method __le__(other: Any) → ColumnOperators
继承自 sqlalchemy.sql.expression.ColumnOperators.__le__ 方法的 ColumnOperators 方法
实现<=运算符。
在列上下文中,生成子句a <= b。
method __lt__(other: Any) → ColumnOperators
继承自 sqlalchemy.sql.expression.ColumnOperators.__lt__ 方法的 ColumnOperators 方法
实现<运算符。
在列上下文中,生成子句a < b。
method __ne__(other: Any) → ColumnOperators
继承自 sqlalchemy.sql.expression.ColumnOperators.__ne__ 方法的 ColumnOperators 方法
实现!=运算符。
在列上下文中,生成子句a != b。如果目标是None,则生成a IS NOT NULL。
method all_() → ColumnOperators
继承自 ColumnOperators.all_() 方法的 ColumnOperators 方法
对父对象生成一个all_()子句。
请参阅all_()的文档以获取示例。
注意
一定不要混淆新的ColumnOperators.all_()方法与此方法的旧版,特定于ARRAY的Comparator.all()方法,它使用不同的调用风格。
method any(criterion: _ColumnExpressionArgument[bool] | None = None, **kwargs: Any) → ColumnElement[bool]
使用 EXISTS 生成一个代理的“any”表达式。
此表达式将使用底层代理属性的Comparator.any()和/或Comparator.has()运算符进行组合乘积。
method any_() → ColumnOperators
继承自 ColumnOperators.any_() 方法的 ColumnOperators
生成一个针对父对象的 any_() 子句。
有关示例,请参阅 any_() 的文档。
注
请务必不要混淆较新的 ColumnOperators.any_() 方法与这个方法的旧版,即 ARRAY 的特定于 Comparator.any() 方法,后者使用了不同的调用风格。
method asc() → ColumnOperators
继承自 ColumnOperators.asc() 方法的 ColumnOperators
生成一个针对父对象的 asc() 子句。
attribute attr
返回一个元组 (local_attr, remote_attr)。
此属性最初旨在促进使用 Query.join() 方法一次加入两个关系,但这使用了已弃用的调用风格。
要使用 select.join() 或 Query.join() 来处理关联代理,当前的方法是分别使用 AssociationProxyInstance.local_attr 和 AssociationProxyInstance.remote_attr 属性:
stmt = ( select(Parent). join(Parent.proxied.local_attr). join(Parent.proxied.remote_attr) )
未来的版本可能会提供更简洁的关联代理属性加入模式。
另请参阅
AssociationProxyInstance.local_attr
AssociationProxyInstance.remote_attr
method between(cleft: Any, cright: Any, symmetric: bool = False) → ColumnOperators
继承自 ColumnOperators.between() 方法,来自于 ColumnOperators
对父对象生成 between() 子句,给定下限和上限范围。
method bitwise_and(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_and() 方法,来自于 ColumnOperators
执行位与操作,通常使用 & 运算符。
版本 2.0.2 中的新功能。
另请参阅
位运算符
method bitwise_lshift(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_lshift() 方法,来自于 ColumnOperators
执行位左移操作,通常使用 << 运算符。
版本 2.0.2 中的新功能。
另请参阅
位运算符
method bitwise_not() → ColumnOperators
继承自 ColumnOperators.bitwise_not() 方法,来自于 ColumnOperators
执行位非操作,通常使用 ~ 运算符。
版本 2.0.2 中的新功能。
另请参阅
位运算符
method bitwise_or(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_or() 方法,来自于 ColumnOperators
执行位或操作,通常使用 | 运算符。
版本 2.0.2 中的新功能。
另请参阅
位运算符
method bitwise_rshift(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_rshift() 方法,来自于 ColumnOperators
执行位右移操作,通常使用 >> 运算符。
版本 2.0.2 中的新功能。
另请参阅
位运算符
method bitwise_xor(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_xor() 方法的 ColumnOperators
执行一个位异或操作,通常通过 ^ 运算符,或 PostgreSQL 上的 # 运算符。
在版本 2.0.2 中新增。
另请参阅
位运算符
method bool_op(opstring: str, precedence: int = 0, python_impl: Callable[[...], Any] | None = None) → Callable[[Any], Operators]
继承自 Operators.bool_op() 方法的 Operators
返回一个自定义布尔运算符。
这个方法是调用 Operators.op() 并传递 Operators.op.is_comparison 标志为 True 的简写。 使用 Operators.bool_op() 的一个关键优势是,在使用列构造时,返回表达式的“布尔”性质将出现在 PEP 484 目的上。
另请参阅
Operators.op()
method collate(collation: str) → ColumnOperators
继承自 ColumnOperators.collate() 方法的 ColumnOperators
对父对象产生一个 collate() 子句,给定排序规则字符串。
另请参阅
collate()
attribute collection_class: Type[Any] | None
method concat(other: Any) → ColumnOperators
继承自 ColumnOperators.concat() 方法的 ColumnOperators
实现‘concat’运算符。
在列上下文中,生成子句 a || b,或在 MySQL 上使用 concat() 运算符。
method contains(other: Any, **kw: Any) → ColumnOperators
继承自 ColumnOperators.contains() 方法,属于 ColumnOperators
实现‘包含’运算符。
生成一个 LIKE 表达式,用于测试字符串值的中间匹配:
column LIKE '%' || <other> || '%'
例如:
stmt = select(sometable).\ where(sometable.c.column.contains("foobar"))
由于运算符使用 LIKE,因此存在于 表达式中的通配符字符 "%" 和 "_" 也将像通配符一样起作用。对于字面字符串值,可以将 ColumnOperators.contains.autoescape 标志设置为 True,以对字符串值中这些字符的出现应用转义,以使它们作为自身而不是通配符字符匹配。另外,ColumnOperators.contains.escape 参数将确立一个给定字符作为转义字符,这在目标表达式不是字面字符串时很有用。
参数:
other– 要比较的表达式。通常这是一个纯字符串值,但也可以是任意的 SQL 表达式。LIKE 通配符字符%和_默认情况下不会转义,除非ColumnOperators.contains.autoescape标志设置为 True。autoescape–
布尔值;当为 True 时,在 LIKE 表达式中建立一个转义字符,然后将其应用于比较值内的所有"%"、"_"和转义字符本身的出现,假定比较值是一个字面字符串而不是 SQL 表达式。
例如:
somecolumn.contains("foo%bar", autoescape=True)
- 渲染结果为:
somecolumn LIKE '%' || :param || '%' ESCAPE '/'
- 使用值
:param作为"foo/%bar"。 escape–
当给定一个字符时,该字符将使用ESCAPE关键字渲染,以将该字符作为转义字符。然后,该字符可以放在%和_的前面,以允许它们充当它们自己而不是通配符字符。
例如:
somecolumn.contains("foo/%bar", escape="^")
- 渲染结果为:
somecolumn LIKE '%' || :param || '%' ESCAPE '^'
- 参数也可以与
ColumnOperators.contains.autoescape结合使用:
somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)
- 在上面的情况下,给定的字面参数将在传递到数据库之前转换为
"foo^%bar^^bat"。
亦参见
ColumnOperators.startswith()
ColumnOperators.endswith()
ColumnOperators.like()
method delete(obj: Any) → None
method desc() → ColumnOperators
继承自 ColumnOperators 方法的 ColumnOperators.desc()
对父对象生成一个 desc() 子句。
method distinct() → ColumnOperators
继承自 ColumnOperators 方法的 ColumnOperators.distinct()
对父对象生成一个 distinct() 子句。
method endswith(other: Any, escape: str | None = None, autoescape: bool = False) → ColumnOperators
继承自 ColumnOperators 方法的 ColumnOperators.endswith()
实现 ‘endswith’ 运算符。
产生一个 LIKE 表达式,用于测试字符串值的结尾匹配:
column LIKE '%' || <other>
例如:
stmt = select(sometable).\ where(sometable.c.column.endswith("foobar"))
由于该运算符使用了 LIKE,所以在 表达式中存在的通配符字符 "%" 和 "_" 也会像通配符一样起作用。对于字面字符串值,可以将 ColumnOperators.endswith.autoescape 标志设置为 True,以将这些字符在字符串值内的出现进行转义,使它们作为自身而不是通配符字符进行匹配。或者,ColumnOperators.endswith.escape 参数将建立一个给定的字符作为转义字符,当目标表达式不是字面字符串时,这可能会有所帮助。
参数:
other– 要进行比较的表达式。通常是一个普通字符串值,但也可以是任意的 SQL 表达式。默认情况下,LIKE 通配符字符%和_不会被转义,除非设置了ColumnOperators.endswith.autoescape标志为 True。autoescape–
布尔值;当为 True 时,在 LIKE 表达式中建立一个转义字符,然后将其应用于比较值中的所有"%"、"_"和转义字符本身的出现,假定比较值是一个文字字符串而不是 SQL 表达式。
一个表达式,例如:
somecolumn.endswith("foo%bar", autoescape=True)
- 将呈现为:
somecolumn LIKE '%' || :param ESCAPE '/'
- 使用值为
:param的"foo/%bar"。 escape–
一个字符,当给定时,将使用ESCAPE关键字来将该字符作为转义字符。然后可以将此字符放在%和_之前,以允许它们作为自身而不是通配符字符。
一个表达式,例如:
somecolumn.endswith("foo/%bar", escape="^")
- 将呈现为:
somecolumn LIKE '%' || :param ESCAPE '^'
- 参数也可以与
ColumnOperators.endswith.autoescape结合使用:
somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的文字参数将在传递到数据库之前转换为
"foo^%bar^^bat"。
另请参阅
ColumnOperators.startswith()
ColumnOperators.contains()
ColumnOperators.like()
classmethod for_proxy(parent: AssociationProxy[_T], owning_class: Type[Any], parent_instance: Any) → AssociationProxyInstance[_T]
method get(obj: Any) → _T | None | AssociationProxyInstance[_T]
method has(criterion: _ColumnExpressionArgument[bool] | None = None, **kwargs: Any) → ColumnElement[bool]
生成一个使用 EXISTS 的代理‘has’表达式。
此表达式将使用基础代理属性的Comparator.any()和/或Comparator.has()运算符进行组合。
method icontains(other: Any, **kw: Any) → ColumnOperators
继承自 ColumnOperators.icontains() 方法的 ColumnOperators
实现icontains运算符,例如ColumnOperators.contains()的不区分大小写版本。
生成一个 LIKE 表达式,用于对字符串值中间的不区分大小写匹配进行测试:
lower(column) LIKE '%' || lower(<other>) || '%'
例如:
stmt = select(sometable).\ where(sometable.c.column.icontains("foobar"))
由于操作符使用了 LIKE,因此在 表达式中出现的通配符字符 "%" 和 "_" 也将像通配符一样起作用。对于文本字符串值,可以将 ColumnOperators.icontains.autoescape 标志设置为 True,以对字符串值中这些字符的出现进行转义,以使它们与自身匹配而不是作为通配符字符。另外,ColumnOperators.icontains.escape 参数将建立一个给定的字符作为转义字符,当目标表达式不是文本字符串时,这可能会有所帮助。
参数:
other– 要比较的表达式。通常是一个普通的字符串值,但也可以是任意的 SQL 表达式。除非设置了ColumnOperators.icontains.autoescape标志为 True,否则 LIKE 通配符%和_默认不会被转义。autoescape–
布尔值;当为 True 时,在 LIKE 表达式中建立一个转义字符,然后将其应用于比较值中所有的"%"、"_"和转义字符本身的出现,假定比较值是一个文本字符串而不是一个 SQL 表达式。
一个表达式如下:
somecolumn.icontains("foo%bar", autoescape=True)
- 将呈现为:
lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'
- 其中
:param的值为"foo/%bar"。 escape–
一个字符,当给定时,将呈现为ESCAPE关键字以将该字符设为转义字符。然后可以将此字符放置在%和_的前面,以允许它们作为自身而不是通配符字符。
一个表达式如下:
somecolumn.icontains("foo/%bar", escape="^")
- 将呈现为:
lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'
- 该参数也可以与
ColumnOperators.contains.autoescape结合使用:
somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的文本参数将在传递到数据库之前转换为
"foo^%bar^^bat"。
另请参见
ColumnOperators.contains()
method iendswith(other: Any, escape: str | None = None, autoescape: bool = False) → ColumnOperators
继承自 ColumnOperators.iendswith() 方法的 ColumnOperators
实现iendswith操作符,例如ColumnOperators.endswith()的不区分大小写版本。
产生一个 LIKE 表达式,用于对字符串值的末尾进行不区分大小写匹配:
lower(column) LIKE '%' || lower(<other>)
例如:
stmt = select(sometable).\ where(sometable.c.column.iendswith("foobar"))
由于该操作符使用LIKE,在表达式中存在的通配符字符"%"和"_"也将像通配符一样行为。对于字面字符串值,可以将ColumnOperators.iendswith.autoescape标志设置为True,以对字符串值内部这些字符的出现进行转义,使它们作为自己而不是通配符字符匹配。或者,ColumnOperators.iendswith.escape参数将建立一个给定字符作为转义字符,这在目标表达式不是字面字符串时可能有用。
参数:
other- 要进行比较的表达式。通常这是一个简单的字符串值,但也可以是任意 SQL 表达式。除非将ColumnOperators.iendswith.autoescape标志设置为 True,否则 LIKE 通配符字符%和_不会被转义。autoescape-
布尔值;当为 True 时,在 LIKE 表达式中建立一个转义字符,然后将其应用于比较值中的所有"%"、"_"和转义字符自身的出现,该比较值假定为字面字符串而不是 SQL 表达式。
诸如以下表达式:
somecolumn.iendswith("foo%bar", autoescape=True)
- 将渲染为:
lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'
- 其值为
:param,为"foo/%bar"。 escape-
给定字符,当使用ESCAPE关键字时,将该字符设定为转义字符。这个字符可以放在%和_之前,以允许它们作为自己而不是通配符字符。
诸如以下表达式:
somecolumn.iendswith("foo/%bar", escape="^")
- 将渲染为:
lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'
- 该参数还可以与
ColumnOperators.iendswith.autoescape结合使用:
somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的字面参数将在传递到数据库之前转换为
"foo^%bar^^bat"。
另请参见
ColumnOperators.endswith()
method ilike(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.ilike() 方法的 ColumnOperators
实现ilike运算符,例如,不区分大小写的 LIKE。
在列上下文中,生成一个形式为的表达式:
lower(a) LIKE lower(other)
或者在支持 ILIKE 运算符的后端上:
a ILIKE other
例如:
stmt = select(sometable).\ where(sometable.c.column.ilike("%foobar%"))
参数:
other– 要比较的表达式escape–
可选的转义字符,呈现ESCAPE关键字,例如:
somecolumn.ilike("foo/%bar", escape="/")
另请参阅
ColumnOperators.like()
method in_(other: Any) → ColumnOperators
继承自 ColumnOperators.in_() 方法的 ColumnOperators
实现in运算符。
在列上下文中,生成子句column IN 。
给定的参数other可能是:
- 一个字面值列表,例如:
stmt.where(column.in_([1, 2, 3]))
- 在这种调用形式中,项目列表被转换为与给定列表长度相同的一组绑定参数:
WHERE COL IN (?, ?, ?)
- 如果比较对象是包含多个表达式的
tuple_()元组列表可以提供:
from sqlalchemy import tuple_ stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
- 一个空列表,例如:
stmt.where(column.in_([]))
- 在这种调用形式中,表达式呈现一个“空集”表达式。这些表达式针对各个后端进行了定制,并且通常试图获得一个空的 SELECT 语句作为子查询。例如,在 SQLite 上,表达式是:
WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
- 版本 1.4 中的更改:现在在所有情况下,空的 IN 表达式都使用执行时生成的 SELECT 子查询。
- 可以使用一个绑定参数,例如
bindparam(),如果它包含bindparam.expanding标志:
stmt.where(column.in_(bindparam('value', expanding=True)))
- 在这种调用形式中,表达式呈现一个特殊的非 SQL 占位符表达式,看起来像:
WHERE COL IN ([EXPANDING_value])
- 此占位符表达式在语句执行时被拦截,转换为前面所示的可变数量的绑定参数形式。如果语句执行为:
connection.execute(stmt, {"value": [1, 2, 3]})
- 数据库将为每个值传递一个绑定参数:
WHERE COL IN (?, ?, ?)
- 版本 1.2 中的新功能:添加了“expanding”绑定参数
如果传递了一个空列表,则会呈现一个特殊的“空列表”表达式,这是特定于正在使用的数据库的。在 SQLite 上,这将是:
WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
- 版本 1.3 中的新功能:现在支持空列表的“expanding”绑定参数
- 一个
select()构造,通常是一个相关的标量选择:
stmt.where( column.in_( select(othertable.c.y). where(table.c.x == othertable.c.x) ) )
- 在这种调用形式中,
ColumnOperators.in_()呈现如下:
WHERE COL IN (SELECT othertable.y FROM othertable WHERE othertable.x = table.x)
参数:
other – 一个文字列表,一个select()构造,或者一个包含设置为 True 的bindparam.expanding标志的bindparam()构造。
attribute info
method is_(other: Any) → ColumnOperators
继承自 ColumnOperators.is_() 方法的 ColumnOperators
实现IS运算符。
通常,当与None的值进行比较时,IS会自动生成,解析为NULL。然而,在某些平台上,如果与布尔值进行比较,则可能希望显式使用IS。
另请参阅
ColumnOperators.is_not()
method is_distinct_from(other: Any) → ColumnOperators
继承自 ColumnOperators.is_distinct_from() 方法的 ColumnOperators
实现IS DISTINCT FROM运算符。
在大多数平台上呈现“a IS DISTINCT FROM b”;在某些平台上如 SQLite 可能呈现“a IS NOT b”。
method is_not(other: Any) → ColumnOperators
继承自 ColumnOperators.is_not() 方法的 ColumnOperators
实现IS NOT运算符。
通常,当与None的值进行比较时,IS NOT会自动生成,解析为NULL。然而,在某些平台上,如果与布尔值进行比较,则可能希望显式使用IS NOT。
从版本 1.4 开始更改:is_not()运算符从先前版本的isnot()重命名。以确保向后兼容性,先前的名称仍然可用。
另请参阅
ColumnOperators.is_()
method is_not_distinct_from(other: Any) → ColumnOperators
继承自 ColumnOperators.is_not_distinct_from() 的 ColumnOperators 方法
实现IS NOT DISTINCT FROM操作符。
大多数平台上会渲染“a IS NOT DISTINCT FROM b”;但在一些平台上如 SQLite 可能会渲染“a IS b”。
在版本 1.4 中更改:is_not_distinct_from()操作符从之前的版本中的isnot_distinct_from()重命名为is_not_distinct_from()。以前的名称仍然可用于向后兼容。
method isnot(other: Any) → ColumnOperators
继承自 ColumnOperators.isnot() 的 ColumnOperators 方法
实现IS NOT操作符。
通常,当与None的值进行比较时,会自动生成IS NOT,它将解析为NULL。然而,在某些平台上,如果与布尔值进行比较,则可能希望明确使用IS NOT。
在版本 1.4 中更改:is_not()操作符从之前的版本中的isnot()重命名为is_not()。以前的名称仍然可用于向后兼容。
另请参阅
ColumnOperators.is_()
method isnot_distinct_from(other: Any) → ColumnOperators
继承自 ColumnOperators.isnot_distinct_from() 的 ColumnOperators 方法
实现IS NOT DISTINCT FROM操作符。
大多数平台上会渲染“a IS NOT DISTINCT FROM b”;但在一些平台上如 SQLite 可能会渲染“a IS b”。
在版本 1.4 中更改:is_not_distinct_from()操作符从之前的版本中的isnot_distinct_from()重命名为is_not_distinct_from()。以前的名称仍然可用于向后兼容。
method istartswith(other: Any, escape: str | None = None, autoescape: bool = False) → ColumnOperators
继承自 ColumnOperators.istartswith() 的 ColumnOperators 方法
实现istartswith操作符,例如ColumnOperators.startswith()的大小写不敏感版本。
生成一个 LIKE 表达式,用于对字符串值的开头进行大小写不敏感匹配测试:
lower(column) LIKE lower(<other>) || '%'
例如:
stmt = select(sometable).\ where(sometable.c.column.istartswith("foobar"))
由于操作符使用 LIKE,所以存在于 表达式中的通配符字符 "%" 和 "_" 也将像通配符一样起作用。对于文字字符串值,可以将 ColumnOperators.istartswith.autoescape 标志设置为 True,以对字符串值内这些字符的出现应用转义,使它们与自身匹配而不是通配符字符。或者,ColumnOperators.istartswith.escape 参数将建立一个给定的字符作为转义字符,当目标表达式不是文字字符串时可能有用。
参数:
other– 要比较的表达式。通常是一个普通的字符串值,但也可以是任意的 SQL 表达式。LIKE 通配符%和_默认情况下不会转义,除非设置了ColumnOperators.istartswith.autoescape标志为 True。autoescape–
布尔值;当为 True 时,在 LIKE 表达式内建立一个转义字符,然后将其应用于比较值内所有的"%"、"_"和转义字符本身的出现,假定比较值为文字字符串而不是 SQL 表达式。
一个表达式,例如:
somecolumn.istartswith("foo%bar", autoescape=True)
- 将渲染为:
lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'
- 其中
:param的值为"foo/%bar"。 escape–
一个字符,当给定时,将以ESCAPE关键字呈现,以将该字符建立为转义字符。然后,可以将此字符放在%和_的前面,以允许它们作为自身而不是通配符字符。
一个表达式,例如:
somecolumn.istartswith("foo/%bar", escape="^")
- 渲染为:
lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'
- 此参数也可以与
ColumnOperators.istartswith.autoescape结合使用:
somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的文字参数将在传递到数据库之前被转换为
"foo^%bar^^bat"。
另请参阅
ColumnOperators.startswith()
method like(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.like() 方法的 ColumnOperators
实现 like 操作符。
在列上下文中,产生表达式:
a LIKE other
例如:
stmt = select(sometable).\ where(sometable.c.column.like("%foobar%"))
参数:
other– 要比较的表达式escape–
可选的转义字符,呈现ESCAPE关键字,例如:
somecolumn.like("foo/%bar", escape="/")
另请参阅
ColumnOperators.ilike()
attribute local_attr
此 AssociationProxyInstance 引用的 ‘local’ 类属性。
另请参阅
AssociationProxyInstance.attr
AssociationProxyInstance.remote_attr
method match(other: Any, **kwargs: Any) → ColumnOperators
继承自 ColumnOperators.match() 方法的 ColumnOperators
实现了特定于数据库的 ‘match’ 操作符。
ColumnOperators.match() 尝试解析为后端提供的 MATCH 类似函数或操作符。例如:
- PostgreSQL - 呈现
x @@ plainto_tsquery(y)
从版本 2.0 开始更改:现在为 PostgreSQL 使用
plainto_tsquery()而不是to_tsquery();为了与其他形式兼容,请参阅 全文搜索。
- MySQL - 呈现
MATCH (x) AGAINST (y IN BOOLEAN MODE)
另请参阅match- 具有附加功能的特定于 MySQL 的构造。 - Oracle - 呈现
CONTAINS(x, y) - 其他后端可能提供特殊实现。
- 没有任何特殊实现的后端将操作符输出为“MATCH”。例如,这与 SQLite 兼容。
method not_ilike(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.not_ilike() 方法的 ColumnOperators
实现 NOT ILIKE 操作符。
这相当于在 ColumnOperators.ilike() 中使用否定,即 ~x.ilike(y)。
从版本 1.4 开始更改:not_ilike() 操作符从先前版本的 notilike() 重命名。之前的名称仍然可用于向后兼容。
另请参阅
ColumnOperators.ilike()
method not_in(other: Any) → ColumnOperators
继承自 ColumnOperators.not_in() 方法的 ColumnOperators
实现NOT IN运算符。
这相当于在ColumnOperators.in_()中使用否定,即~x.in_(y)。
在other是空序列的情况下,编译器会生成一个“空 not in”表达式。默认情况下,这会产生一个“1 = 1”的表达式,以在所有情况下产生 true。可以使用create_engine.empty_in_strategy来更改此行为。
从版本 1.4 开始更改:not_in()运算符从先前版本的notin_()重命名。以确保向后兼容性,先前的名称仍可用。
从版本 1.2 开始更改:ColumnOperators.in_()和ColumnOperators.not_in()运算符现在默认情况下为一个空 IN 序列生成一个“静态”表达式。
另请参阅
ColumnOperators.in_()
method not_like(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.not_like() 方法的 ColumnOperators
实现NOT LIKE运算符。
这相当于在ColumnOperators.like()中使用否定,即~x.like(y)。
从版本 1.4 开始更改:not_like()运算符从先前版本的notlike()重命名。以确保向后兼容性,先前的名称仍可用。
另请参阅
ColumnOperators.like()
method notilike(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.notilike() 方法的 ColumnOperators
实现NOT ILIKE运算符。
这等同于使用 ColumnOperators.ilike() 进行否定,即 ~x.ilike(y)。
从版本 1.4 开始更改:not_ilike() 操作符从先前版本的 notilike() 重命名。以确保向后兼容性,先前的名称仍然可用。
另请参阅
ColumnOperators.ilike()
method notin_(other: Any) → ColumnOperators
继承自 ColumnOperators.notin_() 方法的 ColumnOperators
实现 NOT IN 操作符。
这等同于使用 ColumnOperators.in_() 进行否定,即 ~x.in_(y)。
如果 other 是一个空序列,则编译器会生成一个“空的不在”表达式。默认情况下,这等同于表达式“1 = 1”,在所有情况下都返回 true。可以使用 create_engine.empty_in_strategy 来更改此行为。
从版本 1.4 开始更改:not_in() 操作符从先前版本的 notin_() 重命名。以确保向后兼容性,先前的名称仍然可用。
从版本 1.2 开始更改:ColumnOperators.in_() 和 ColumnOperators.not_in() 操作符现在默认情况下为一个空的 IN 序列生成一个“静态”表达式。
另请参阅
ColumnOperators.in_()
method notlike(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.notlike() 方法的 ColumnOperators
实现 NOT LIKE 操作符。
这等同于使用 ColumnOperators.like() 进行否定,即 ~x.like(y)。
从版本 1.4 开始更改:not_like() 操作符从先前版本的 notlike() 重命名。以确保向后兼容性,先前的名称仍然可用。
另请参阅
ColumnOperators.like()
method nulls_first() → ColumnOperators
继承自 ColumnOperators.nulls_first() 方法的 ColumnOperators
对父对象生成一个nulls_first()子句。
1.4 版本更改:nulls_first()运算符在先前版本中从nullsfirst()重命名。以确保向后兼容性,先前的名称仍然可用。
method nulls_last() → ColumnOperators
继承自 ColumnOperators.nulls_last() 方法的 ColumnOperators
对父对象生成一个nulls_last()子句。
1.4 版本更改:nulls_last()运算符在先前版本中从nullslast()重命��。以确保向后兼容性,先前的名称仍然可用。
method nullsfirst() → ColumnOperators
继承自 ColumnOperators.nullsfirst() 方法的 ColumnOperators
对父对象生成一个nulls_first()子句。
1.4 版本更改:nulls_first()运算符在先前版本中从nullsfirst()重命名。以确保向后兼容性,先前的名称仍然可用。
method nullslast() → ColumnOperators
继承自 ColumnOperators.nullslast() 方法的 ColumnOperators
对父对象生成一个nulls_last()子句。
1.4 版本更改:nulls_last()运算符在先前版本中从nullslast()重命名。以确保向后兼容性,先前的名称仍然可用。
method op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Type[TypeEngine[Any]] | TypeEngine[Any] | None = None, python_impl: Callable[..., Any] | None = None) → Callable[[Any], Operators]
继承自 Operators.op() 方法的 Operators
生成一个通用的运算符函数。
例如:
somecolumn.op("*")(5)
产生:
somecolumn * 5
这个函数也可以用来使位运算符明确。例如:
somecolumn.op('&')(0xff)
是somecolumn中值的按位与。
参数:
opstring– 一个字符串,将作为中缀运算符输出在此元素和传递给生成函数的表达式之间。precedence–
预期数据库在 SQL 表达式中应用于运算符的优先级。这个整数值作为 SQL 编译器的提示,用于确定何时应该在特定操作周围渲染显式括号。较低的数字将导致在应用于具有更高优先级的另一个运算符时对表达式进行括号化。默认值为0,低于所有运算符,除了逗号(,)和AS运算符。值为 100 将高于或等于所有运算符,-100 将低于或等于所有运算符。
另请参见
我正在使用op()生成自定义运算符,但我的括号没有正确显示 - SQLAlchemy SQL 编译器如何渲染括号的详细描述is_comparison–
传统; 如果为 True,则将运算符视为“比较”运算符,即评估为布尔真/假值的运算符,如==,>等。提供此标志是为了 ORM 关系可以在自定义连接条件中使用运算符时建立该运算符是比较运算符。
使用is_comparison参数已被使用Operators.bool_op()方法取代;这个更简洁的运算符会自动设置此参数,但也提供了正确的PEP 484类型支持,因为返回的对象将表示“布尔”数据类型,即BinaryExpression[bool]。return_type– 一个TypeEngine类或对象,将强制此运算符生成的表达式的返回类型为该类型。默认情况下,指定Operators.op.is_comparison的运算符将解析为Boolean,而未指定的运算符将与左操作数的类型相同。python_impl–
可选的 Python 函数,可以像数据库服务器上运行此操作符时的工作方式一样评估两个 Python 值。适用于在 Python 中的 SQL 表达式评估函数,例如用于 ORM 混合属性的,以及在多行更新或删除后用于匹配会话中的对象的 ORM“评估器”。
例如:
>>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')
- 上述表达式的操作符也将适用于非 SQL 左侧和右侧对象:
>>> expr.operator(5, 10) 15
- 从 2.0 版开始。
另请参见
Operators.bool_op()
重新定义和创建新的操作符
在联接条件中使用自定义操作符
method operate(op: OperatorType, *other: Any, **kwargs: Any) → Operators
继承自 Operators.operate() 方法的 Operators
对一个参数进行操作。
这是操作的最低级别,默认会引发 NotImplementedError。
在子类上覆盖此操作可以允许将常见行为应用于所有操作。例如,覆盖 ColumnOperators 以将 func.lower() 应用于左右两侧:
class MyComparator(ColumnOperators): def operate(self, op, other, **kwargs): return op(func.lower(self), func.lower(other), **kwargs)
参数:
op– 操作符可调用。*other– 操作的‘其他’一侧。 对于大多数操作,将是单个标量。**kwargs– 修饰符。这些可以通过特殊操作符传递,如ColumnOperators.contains()。
attribute parent: _AssociationProxyProtocol[_T]
method regexp_match(pattern: Any, flags: str | None = None) → ColumnOperators
继承自 ColumnOperators.regexp_match() 方法的 ColumnOperators
实现了一个特定于数据库的‘正则匹配’操作符。
例如:
stmt = select(table.c.some_column).where( table.c.some_column.regexp_match('^(b|c)') )
ColumnOperators.regexp_match() 尝试解析为由后端提供的类似 REGEXP 的函数或操作符,但是具体的正则表达式语法和可用标志与后端无关。
示例包括:
- PostgreSQL - 在否定时渲染
x ~ y或x !~ y。 - Oracle - 渲染
REGEXP_LIKE(x, y) - SQLite - 使用 SQLite 的
REGEXP占位符操作符并调用 Python 的re.match()内建函数。 - 其他后端可能提供特殊实现。
- 没有任何特殊实现的后端将将操作符发出为“REGEXP”或“NOT REGEXP”。 例如,这与 SQLite 和 MySQL 兼容。
目前 Oracle、PostgreSQL、MySQL 和 MariaDB 均已实现了正则表达式支持。SQLite 部分支持。第三方方言中的支持可能有所不同。
参数:
pattern– 正则表达式模式字符串或列子句。flags– 要应用的任何正则表达式字符串标志,仅作为普通 Python 字符串传递。这些标志是特定于后端的。某些后端,如 PostgreSQL 和 MariaDB,可能会将标志作为模式的一部分来指定。在 PostgreSQL 中使用忽略大小写标志‘i’时,将使用忽略大小写的正则表达式匹配运算符~*或!~*。
版本 1.4 中的新功能。
在版本 1.4.48 更改:2.0.18 请注意,由于实现错误,“flags”参数先前接受了 SQL 表达式对象,例如列表达式,除了普通的 Python 字符串。此实现与缓存不兼容,并已删除;应仅传递字符串作为“flags”参数,因为这些标志将作为 SQL 表达式中的文字内联值呈现。
另请参见
ColumnOperators.regexp_replace()
method regexp_replace(pattern: Any, replacement: Any, flags: str | None = None) → ColumnOperators
继承自 ColumnOperators.regexp_replace() 方法的 ColumnOperators
实现了特定于数据库的“regexp replace”运算符。
例如:
stmt = select( table.c.some_column.regexp_replace( 'b(..)', 'XY', flags='g' ) )
ColumnOperators.regexp_replace() 试图解析为后端提供的类似 REGEXP_REPLACE 的函数,通常会生成函数REGEXP_REPLACE()。然而,特定的正则表达式语法和可用的标志不是后端通用的。
目前 Oracle、PostgreSQL、MySQL 8 或更高版本和 MariaDB 均已实现了正则表达式替换支持。第三方方言中的支持可能有所不同。
参数:
pattern– 正则表达式模式字符串或列子句。pattern– 替换字符串或列子句。flags– 要应用的任何正则表达式字符串标志,仅作为普通 Python 字符串传递。这些标志是特定于后端的。某些后端,如 PostgreSQL 和 MariaDB,可能会将标志作为模式的一部分来指定。
版本 1.4 中的新功能。
从版本 1.4.48 更改为:2.0.18 请注意,由于实现错误,之前的“flags”参数接受了 SQL 表达式对象,例如列表达式,而不仅仅是普通的 Python 字符串。该实现与缓存一起不正确地工作,并已删除;仅应传递字符串作为“flags”参数,因为这些标志被渲染为 SQL 表达式中的文字内联值。
另请参阅
ColumnOperators.regexp_match()
attribute remote_attr
此AssociationProxyInstance引用的“remote”类属性。
另请参阅
AssociationProxyInstance.attr
AssociationProxyInstance.local_attr
method reverse_operate(op: OperatorType, other: Any, **kwargs: Any) → Operators
继承自 Operators.reverse_operate() 方法的 Operators
在参数上执行反向操作。
用法与operate()相同。
attribute scalar
如果此AssociationProxyInstance代理了本地一侧的标量关系,则返回True。
method set(obj: Any, values: _T) → None
method startswith(other: Any, escape: str | None = None, autoescape: bool = False) → ColumnOperators
继承自 ColumnOperators.startswith() 方法的 ColumnOperators
实现startswith运算符。
生成一个 LIKE 表达式,用于测试字符串值的开头匹配:
column LIKE <other> || '%'
例如:
stmt = select(sometable).\ where(sometable.c.column.startswith("foobar"))
由于该操作员使用 LIKE,所以在 表达式内存在的通配符字符 "%" 和 "_" 也将像通配符一样运行。对于文字字符串值,可以将 ColumnOperators.startswith.autoescape 标志设置为 True,以对字符串值中这些字符的出现进行转义,使它们作为自身而不是通配符字符匹配。或者,ColumnOperators.startswith.escape 参数将建立一个给定的字符作为转义字符,这在目标表达式不是文字字符串时可能会有用。
参数:
other– 要比较的表达式。这通常是一个简单的字符串值,但也可以是任意的 SQL 表达式。默认情况下,LIKE 通配符字符%和_不被转义,除非ColumnOperators.startswith.autoescape标志被设置为 True。autoescape–
布尔值;当为 True 时,在 LIKE 表达式中建立一个转义字符,然后将其应用于比较值中的所有出现的"%"、"_"和转义字符本身,假定比较值是一个文字字符串而不是一个 SQL 表达式。
一个表达式,例如:
somecolumn.startswith("foo%bar", autoescape=True)
- 将渲染为:
somecolumn LIKE :param || '%' ESCAPE '/'
- 使用值为
:param的"foo/%bar"。 escape–
一个字符,当给定时,将使用ESCAPE关键字将该字符设定为转义字符。然后可以将此字符放置在%和_出现之前,以使它们可以作为自己而不是通配符字符。
一个表达式,例如:
somecolumn.startswith("foo/%bar", escape="^")
- 将渲染为:
somecolumn LIKE :param || '%' ESCAPE '^'
- 参数也可以与
ColumnOperators.startswith.autoescape结合使用:
somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的文字参数在传递到数据库之前将被转换为
"foo^%bar^^bat"。
另请参阅
ColumnOperators.endswith()
ColumnOperators.contains()
ColumnOperators.like()
attribute target_class: Type[Any]
此AssociationProxyInstance处理的中间类。
拦截的追加/设置/赋值事件将导致生成此类的新实例。
attribute timetuple: Literal[None] = None
继承自 ColumnOperators.timetuple 属性的 ColumnOperators
Hack,允许在左侧比较日期时间对象。
class sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance
一个AssociationProxyInstance,其目标是一个对象。
成员
le(), lt(), all_(), any(), any_(), asc(), attr, between(), bitwise_and(), bitwise_lshift(), bitwise_not(), bitwise_or(), bitwise_rshift(), bitwise_xor(), bool_op(), collate(), concat(), contains(), desc(), distinct(), endswith(), has(), icontains(), iendswith(), ilike(), in_(), is_(), is_distinct_from(), is_not(), is_not_distinct_from(), isnot(), isnot_distinct_from(), istartswith(), like(), local_attr, match(), not_ilike(), not_in(), not_like(), notilike(), notin_(), notlike(), nulls_first(), nulls_last(), nullsfirst(), nullslast(), op(), operate(), regexp_match(), regexp_replace(), remote_attr, reverse_operate(), scalar, startswith(), target_class, timetuple
类签名
类sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance(sqlalchemy.ext.associationproxy.AssociationProxyInstance)
method __le__(other: Any) → ColumnOperators
继承自 ColumnOperators 的 sqlalchemy.sql.expression.ColumnOperators.__le__ 方法
实现 <= 操作符。
在列上下文中,生成子句 a <= b。
method __lt__(other: Any) → ColumnOperators
继承自 ColumnOperators 的 sqlalchemy.sql.expression.ColumnOperators.__lt__ 方法
实现 < 操作符。
在列上下文中,生成子句 a < b。
method all_() → ColumnOperators
继承自 ColumnOperators 的 ColumnOperators.all_() 方法
对父对象生成一个 all_() 子句。
请查看all_()的文档以获取示例。
注意
不要混淆较新的ColumnOperators.all_()方法与旧版本该方法,即特定于ARRAY的Comparator.all()方法,后者使用不同的调用风格。
method any(criterion: _ColumnExpressionArgument[bool] | None = None, **kwargs: Any) → ColumnElement[bool]
继承自 AssociationProxyInstance 的 AssociationProxyInstance.any() 方法
使用 EXISTS 生成代理的‘any’表达式。
此表达式将使用底层代理属性的Comparator.any()和/或Comparator.has()操作符进行组合。
method any_() → ColumnOperators
继承自 ColumnOperators 的 ColumnOperators.any_() 方法
对父对象生成一个any_()子句。
有关示例,请参阅any_()的文档。
注意
请务必不要混淆较新的ColumnOperators.any_()方法与此方法的旧版,即Comparator.any()方法,后者特定于ARRAY,其使用了不同的调用样式。
method asc() → ColumnOperators
继承自 ColumnOperators.asc() 方法的 ColumnOperators
对父对象生成一个asc()子句。
attribute attr
继承自 AssociationProxyInstance.attr 属性的 AssociationProxyInstance
返回一个元组(local_attr, remote_attr)。
此属性最初旨在方便使用Query.join()方法同时跨两个关系进行连接,但这使用了已弃用的调用样式。
要使用select.join()或Query.join()与关联代理,当前方法是分别利用AssociationProxyInstance.local_attr和AssociationProxyInstance.remote_attr属性:
stmt = ( select(Parent). join(Parent.proxied.local_attr). join(Parent.proxied.remote_attr) )
未来的一个版本可能会提供更简洁的关联代理属性连接模式。
另请参阅
AssociationProxyInstance.local_attr
AssociationProxyInstance.remote_attr
method between(cleft: Any, cright: Any, symmetric: bool = False) → ColumnOperators
继承自 ColumnOperators.between() 方法的 ColumnOperators
对父对象执行between() 子句,给定下限和上限范围。
method bitwise_and(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_and() 方法的 ColumnOperators
执行位与操作,通常使用&运算符。
自版本 2.0.2 新增。
另请参阅
位运算符
method bitwise_lshift(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_lshift() 方法的 ColumnOperators
执行位左移操作,通常使用<<运算符。
自版本 2.0.2 新增。
另请参阅
位运算符
method bitwise_not() → ColumnOperators
继承自 ColumnOperators.bitwise_not() 方法的 ColumnOperators
执行位非操作,通常使用~运算符。
自版本 2.0.2 新增。
另请参阅
位运算符
method bitwise_or(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_or() 方法的 ColumnOperators
执行位或操作,通常使用|运算符。
自版本 2.0.2 新增。
另请参阅
位运算符
method bitwise_rshift(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_rshift() 方法的 ColumnOperators
执行位右移操作,通常使用>>运算符。
自版本 2.0.2 新增。
另请参阅
位运算符
method bitwise_xor(other: Any) → ColumnOperators
继承自 ColumnOperators.bitwise_xor() 方法的 ColumnOperators
生成按位异或运算,通常通过^运算符,或者对于 PostgreSQL 使用#。
版本 2.0.2 中的新功能。
另请参阅
位运算符
method bool_op(opstring: str, precedence: int = 0, python_impl: Callable[[...], Any] | None = None) → Callable[[Any], Operators]
继承自 Operators.bool_op() 方法的 Operators
返回自定义布尔运算符。
此方法是调用 Operators.op() 并传递 Operators.op.is_comparison 标志为 True 的快捷方式。使用 Operators.bool_op() 的一个关键优势是,当使用列构造时,返回表达式的“布尔”性质将存在于PEP 484目的中。
另请参阅
Operators.op()
method collate(collation: str) → ColumnOperators
继承自 ColumnOperators.collate() 方法的 ColumnOperators
根据给定的排序字符串生成针对父对象的 collate() 子句。
另请参阅
collate()
method concat(other: Any) → ColumnOperators
继承自 ColumnOperators.concat() 方法的 ColumnOperators
实现‘concat’运算符。
在列上下文中,生成子句a || b,或在 MySQL 上使用concat()运算符。
method contains(other: Any, **kw: Any) → ColumnElement[bool]
使用 EXISTS 生成代理的“包含”表达式。
此表达式将使用基础代理属性的Comparator.any()、Comparator.has()和/或Comparator.contains()操作符进行组合。
method desc() → ColumnOperators
继承自 ColumnOperators.desc() 方法的 ColumnOperators
生成针对父对象的desc()子句。
method distinct() → ColumnOperators
继承自 ColumnOperators.distinct() 方法的 ColumnOperators
生成针对父对象的distinct()子句。
method endswith(other: Any, escape: str | None = None, autoescape: bool = False) → ColumnOperators
继承自 ColumnOperators.endswith() 方法的 ColumnOperators
实现‘endswith’操作符。
生成一个 LIKE 表达式,测试字符串值的结尾是否匹配:
column LIKE '%' || <other>
例如:
stmt = select(sometable).\ where(sometable.c.column.endswith("foobar"))
由于操作符使用LIKE,存在于表达式中的通配符字符"%"和"_"也将像通配符一样起作用。对于字面字符串值,ColumnOperators.endswith.autoescape标志可以设置为True,以对字符串值中这些字符的出现进行转义,使它们匹配为它们自身而不是通配符字符。或者,ColumnOperators.endswith.escape参数将建立一个给定字符作为转义字符,当目标表达式不是字面字符串时,这可能会有用。
参数:
other– 要比较的表达式。这通常是一个简单的字符串值,但也可以是任意的 SQL 表达式。除非将ColumnOperators.endswith.autoescape标志设置为 True,否则 LIKE 通配符字符%和_不会被转义。autoescape–
布尔值;当为 True 时,在 LIKE 表达式内建立转义字符,然后将其应用于比较值中所有的"%"、"_"和转义字符本身的出现次数,假定比较值是一个字面字符串而不是一个 SQL 表达式。
一个表达式,例如:
somecolumn.endswith("foo%bar", autoescape=True)
- 将呈现为:
somecolumn LIKE '%' || :param ESCAPE '/
- 值为
:param,值为"foo/%bar"。 escape–
一个字符,当给定时,将使用ESCAPE关键字来建立该字符作为转义字符。然后可以将此字符放置在%和_的前面,以允许它们作为自身而不是通配符字符。
一个表达式,例如:
somecolumn.endswith("foo/%bar", escape="^")
- 将呈现为:
somecolumn LIKE '%' || :param ESCAPE '^'
- 该参数也可以与
ColumnOperators.endswith.autoescape结合使用:
somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的字面参数将在传递到数据库之前转换为
"foo^%bar^^bat"。
另请参阅
ColumnOperators.startswith()
ColumnOperators.contains()
ColumnOperators.like()
method has(criterion: _ColumnExpressionArgument[bool] | None = None, **kwargs: Any) → ColumnElement[bool]
继承自 AssociationProxyInstance.has() 方法的 AssociationProxyInstance
使用 EXISTS 生成一个代理的“has”表达式。
此表达式将使用底层代理属性的Comparator.any()和/或Comparator.has()操作符的组合产品。
method icontains(other: Any, **kw: Any) → ColumnOperators
继承自 ColumnOperators.icontains() 方法的 ColumnOperators
实现icontains运算符,例如 ColumnOperators.contains() 的不区分大小写版本。
生成一个 LIKE 表达式,用于对字符串值中间进行不区分大小写的匹配测试:
lower(column) LIKE '%' || lower(<other>) || '%'
例如:
stmt = select(sometable).\ where(sometable.c.column.icontains("foobar"))
由于运算符使用LIKE,存在于表达式内部的通配符字符"%"和"_"也将像通配符一样行事。对于字面字符串值,可以将ColumnOperators.icontains.autoescape标志设置为True,以对字符串值内这些字符的出现进行转义,使其与自身而不是通配符字符匹配。或者,ColumnOperators.icontains.escape参数将建立一个给定字符作为转义字符,当目标表达式不是字面字符串时,这可能会有用。
参数:
other– 要比较的表达式。通常这是一个简单的字符串值,但也可以是任意的 SQL 表达式。LIKE 通配符%和_默认情况下不会转义,除非设置了ColumnOperators.icontains.autoescape标志为 True。autoescape–
boolean;当为 True 时,在 LIKE 表达式中建立一个转义字符,然后将其应用于比较值内所有的"%"、"_"和转义字符本身,假定比较值是一个字面字符串而不是一个 SQL 表达式。
例如表达式:
somecolumn.icontains("foo%bar", autoescape=True)
- 将渲染为:
lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'
- 其中
param的值为"foo/%bar"。 escape–
一个字符,当给定时,将使用ESCAPE关键字将其渲染为转义字符。然后,可以将此字符放置在%和_之前,以允许它们作为自身而不是通配符字符。
例如表达式:
somecolumn.icontains("foo/%bar", escape="^")
- 将渲染为:
lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'
- 该参数也可以与
ColumnOperators.contains.autoescape结合使用:
somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的字面参数将在传递到数据库之前转换为
"foo^%bar^^bat"。
另请参阅
ColumnOperators.contains()
method iendswith(other: Any, escape: str | None = None, autoescape: bool = False) → ColumnOperators
继承自 ColumnOperators.iendswith() 方法的 ColumnOperators
实现 iendswith 操作符,例如 ColumnOperators.endswith() 的不区分大小写版本。
生成一个 LIKE 表达式,对字符串值的末尾进行不区分大小写匹配:
lower(column) LIKE '%' || lower(<other>)
例如:
stmt = select(sometable).\ where(sometable.c.column.iendswith("foobar"))
由于操作符使用了 LIKE,存在于 表达式内部的通配符 "%" 和 "_" 也将像通配符一样运行。对于文字字符串值,可以将 ColumnOperators.iendswith.autoescape 标志设置为 True,以对字符串值中这些字符的出现进行转义,使它们匹配为自身而不是通配符。另外,ColumnOperators.iendswith.escape 参数将建立一个给定的字符作为转义字符,当目标表达式不是文字字符串时可能会有用。
参数:
other– 需要进行比较的表达式。通常是一个普通的字符串值,但也可以是任意的 SQL 表达式。LIKE通配符%和_默认情况下不会被转义,除非ColumnOperators.iendswith.autoescape标志被设置为True。autoescape–
布尔值;当为True时,在LIKE表达式中建立一个转义字符,然后将其应用于比较值内的所有"%"、"_"和转义字符本身的出现,假定比较值为文字字符串而不是 SQL 表达式。
如下表达式:
somecolumn.iendswith("foo%bar", autoescape=True)
- 渲染为:
lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'
- 将值为
:param的值设为"foo/%bar"。 escape–
给定一个字符,当给定时将使用ESCAPE关键字将其设置为转义字符。然后可以将此字符放在%和_的出现之前,以允许它们作为自身而不是通配符字符。
如下表达式:
somecolumn.iendswith("foo/%bar", escape="^")
- 渲染为:
lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'
- 参数也可以与
ColumnOperators.iendswith.autoescape结合使用:
somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)
- 在上述情况下,给定的文字参数将在传递到数据库之前被转换为
"foo^%bar^^bat"。
另请参阅
ColumnOperators.endswith()
method ilike(other: Any, escape: str | None = None) → ColumnOperators
继承自 ColumnOperators.ilike() 的 ColumnOperators 方法
实现ilike运算符,例如,不区分大小写的 LIKE。
在列上下文中,产生形式之一的表达式:
lower(a) LIKE lower(other)
或在支持 ILIKE 运算符的后端上:
a ILIKE other
例如:
stmt = select(sometable).\ where(sometable.c.column.ilike("%foobar%"))
参数:
other- 要比较的表达式escape-
可选的转义字符,呈现ESCAPE关键字,例如:
somecolumn.ilike("foo/%bar", escape="/")
另请参阅
ColumnOperators.like()
method in_(other: Any) → ColumnOperators
继承自 ColumnOperators.in_() 的 ColumnOperators 方法
实现in运算符。
在列上下文中,产生子句 column IN 。
给定参数 other 可能是:
- 字面值列表,例如:
stmt.where(column.in_([1, 2, 3]))
- 在此调用形式中,项目列表被转换为与给定列表长度相同的一组绑定参数:
WHERE COL IN (?, ?, ?)
- 如果比较是针对包含多个表达式的
tuple_(),可以提供元组的列表:
from sqlalchemy import tuple_ stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
- 一个空列表,例如:
stmt.where(column.in_([]))
- 在此调用形式中,表达式呈现一个“空集”表达式。这些表达式针对各个后端进行了定制,并且通常试图获得一个空的 SELECT 语句作为子查询。例如,在 SQLite 上,表达式为:
WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
- 1.4 版本中的更改:在所有情况下,空的 IN 表达式现在都使用执行时生成的 SELECT 子查询。
- 如果包含
bindparam.expanding标志,可以使用绑定参数,例如bindparam():
stmt.where(column.in_(bindparam('value', expanding=True)))
- 在此调用形式中,表达式呈现一个特殊的非 SQL 占位符表达式,如下所示:
WHERE COL IN ([EXPANDING_value])
- 此占位符表达式在语句执行时拦截,以转换为前面所示的可变数量的绑定参数形式。如果语句执行为:
connection.execute(stmt, {"value": [1, 2, 3]})
- 数据库将为每个值传递一个绑定参数:
WHERE COL IN (?, ?, ?)
- 1.2 版本中的新功能:添加了“扩展”绑定参数
如果传递了一个空列表,将呈现一个特殊的“空列表”表达式,该表达式特定于正在使用的数据库。在 SQLite 上,这将是:
WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)
- 1.3 版本中的新功能:现在“扩展”绑定参数支持空列表
select()构造,通常是相关的标量选择:
stmt.where( column.in_( select(othertable.c.y). where(table.c.x == othertable.c.x) ) )
- 在这种调用形式中,
ColumnOperators.in_()如下所示:
WHERE COL IN (SELECT othertable.y FROM othertable WHERE othertable.x = table.x)
SqlAlchemy 2.0 中文文档(二十九)(5)https://developer.aliyun.com/article/1560469