Association Proxy

    Consider a many-to-many mapping between two classes, User and Keyword. Each User can have any number of Keyword objects, and vice-versa (the many-to-many pattern is described at ). The example below illustrates this pattern in the same way, with the exception of an extra attribute added to the User class called User.keywords:

    In the above example, association_proxy() is applied to the User class to produce a “view” of the kw relationship, which exposes the string value of .keyword associated with each Keyword object. It also creates new Keyword objects transparently when strings are added to the collection:

    1. >>> user = User("jek")
    2. >>> user.keywords.append("cheese-inspector")
    3. >>> user.keywords.append("snack-ninja")
    4. >>> print(user.keywords)
    5. ['cheese-inspector', 'snack-ninja']

    To understand the mechanics of this, first review the behavior of User and Keyword without using the .keywords association proxy. Normally, reading and manipulating the collection of “keyword” strings associated with User requires traversal from each collection element to the .keyword attribute, which can be awkward. The example below illustrates the identical series of operations applied without using the association proxy:

    1. >>> # identical operations without using the association proxy
    2. >>> user = User("jek")
    3. >>> user.kw.append(Keyword("cheese-inspector"))
    4. >>> user.kw.append(Keyword("snack-ninja"))
    5. >>> print([keyword.keyword for keyword in user.kw])
    6. ['cheese-inspector', 'snack-ninja']

    The object produced by the association_proxy() function is an instance of a , and is not considered to be “mapped” by the Mapper in any way. Therefore, it’s always indicated inline within the class definition of the mapped class, regardless of whether Declarative or Imperative mappings are used.

    The proxy functions by operating upon the underlying mapped attribute or collection in response to operations, and changes made via the proxy are immediately apparent in the mapped attribute, as well as vice versa. The underlying attribute remains fully accessible.

    When first accessed, the association proxy performs introspection operations on the target collection so that its behavior corresponds correctly. Details such as if the locally proxied attribute is a collection (as is typical) or a scalar reference, as well as if the collection acts like a set, list, or dictionary is taken into account, so that the proxy should act just like the underlying collection or attribute does.

    Creation of New Values

    When a list append() event (or set add(), dictionary __setitem__(), or scalar assignment event) is intercepted by the association proxy, it instantiates a new instance of the “intermediary” object using its constructor, passing as a single argument the given value. In our example above, an operation like:

    1. user.keywords.append("cheese-inspector")

    Is translated by the association proxy into the operation:

    1. user.kw.append(Keyword("cheese-inspector"))

    The example works here because we have designed the constructor for Keyword to accept a single positional argument, keyword. For those cases where a single-argument constructor isn’t feasible, the association proxy’s creational behavior can be customized using the association_proxy.creator argument, which references a callable (i.e. Python function) that will produce a new object instance given the singular argument. Below we illustrate this using a lambda as is typical:

    1. class User(Base):
    2. ...
    3. # use Keyword(keyword=kw) on append() events
    4. keywords: AssociationProxy[list[str]] = association_proxy(
    5. "kw", "keyword", creator=lambda kw: Keyword(keyword=kw)
    6. )

    The creator function accepts a single argument in the case of a list- or set- based collection, or a scalar attribute. In the case of a dictionary-based collection, it accepts two arguments, “key” and “value”. An example of this is below in .

    The “association object” pattern is an extended form of a many-to-many relationship, and is described at . Association proxies are useful for keeping “association objects” out of the way during regular use.

    Suppose our user_keyword table above had additional columns which we’d like to map explicitly, but in most cases we don’t require direct access to these attributes. Below, we illustrate a new mapping which introduces the UserKeywordAssociation class, which is mapped to the user_keyword table illustrated earlier. This class adds an additional column special_key, a value which we occasionally want to access, but not in the usual case. We create an association proxy on the User class called keywords, which will bridge the gap from the user_keyword_associations collection of User to the .keyword attribute present on each UserKeywordAssociation:

    1. from __future__ import annotations
    2. from typing import Optional
    3. from sqlalchemy import ForeignKey
    4. from sqlalchemy import String
    5. from sqlalchemy.ext.associationproxy import association_proxy
    6. from sqlalchemy.ext.associationproxy import AssociationProxy
    7. from sqlalchemy.orm import DeclarativeBase
    8. from sqlalchemy.orm import Mapped
    9. from sqlalchemy.orm import mapped_column
    10. from sqlalchemy.orm import relationship
    11. class Base(DeclarativeBase):
    12. pass
    13. class User(Base):
    14. __tablename__ = "user"
    15. id: Mapped[int] = mapped_column(primary_key=True)
    16. name: Mapped[str] = mapped_column(String(64))
    17. user_keyword_associations: Mapped[list[UserKeywordAssociation]] = relationship(
    18. back_populates="user",
    19. cascade="all, delete-orphan",
    20. )
    21. # association proxy of "user_keyword_associations" collection
    22. # to "keyword" attribute
    23. keywords: AssociationProxy[list[Keyword]] = association_proxy(
    24. "user_keyword_associations",
    25. "keyword",
    26. creator=lambda keyword: UserKeywordAssociation(keyword=Keyword(keyword)),
    27. )
    28. def __init__(self, name: str):
    29. self.name = name
    30. class UserKeywordAssociation(Base):
    31. __tablename__ = "user_keyword"
    32. user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), primary_key=True)
    33. keyword_id: Mapped[int] = mapped_column(ForeignKey("keyword.id"), primary_key=True)
    34. special_key: Mapped[Optional[str]] = mapped_column(String(50))
    35. user: Mapped[User] = relationship(back_populates="user_keyword_associations")
    36. keyword: Mapped[Keyword] = relationship()
    37. class Keyword(Base):
    38. __tablename__ = "keyword"
    39. id: Mapped[int] = mapped_column(primary_key=True)
    40. keyword: Mapped[str] = mapped_column("keyword", String(64))
    41. def __init__(self, keyword: str):
    42. self.keyword = keyword
    43. def __repr__(self) -> str:
    44. return f"Keyword({self.keyword!r})"

    With the above configuration, we can operate upon the .keywords collection of each User object, each of which exposes a collection of Keyword objects that are obtained from the underlying UserKeywordAssociation elements:

    1. >>> user = User("log")
    2. >>> for kw in (Keyword("new_from_blammo"), Keyword("its_big")):
    3. ... user.keywords.append(kw)
    4. >>> print(user.keywords)
    5. [Keyword('new_from_blammo'), Keyword('its_big')]

    This example is in contrast to the example illustrated previously at Simplifying Scalar Collections, where the association proxy exposed a collection of strings, rather than a collection of composed objects. In this case, each .keywords.append() operation is equivalent to:

    1. >>> user.user_keyword_associations.append(
    2. ... UserKeywordAssociation(keyword=Keyword("its_heavy"))
    3. ... )

    The UserKeywordAssociation object has two attributes that are both populated within the scope of the append() operation of the association proxy; .keyword, which refers to the Keyword object, and .user, which refers to the User object. The .keyword attribute is populated first, as the association proxy generates a new UserKeywordAssociation object in response to the .append() operation, assigning the given Keyword instance to the .keyword attribute. Then, as the UserKeywordAssociation object is appended to the User.user_keyword_associations collection, the UserKeywordAssociation.user attribute, configured as back_populates for User.user_keyword_associations, is initialized upon the given UserKeywordAssociation instance to refer to the parent User receiving the append operation. The special_key argument above is left at its default value of None.

    For those cases where we do want special_key to have a value, we create the UserKeywordAssociation object explicitly. Below we assign all three attributes, wherein the assignment of .user during construction, has the effect of appending the new UserKeywordAssociation to the User.user_keyword_associations collection (via the relationship):

    1. >>> UserKeywordAssociation(
    2. ... keyword=Keyword("its_wood"), user=user, special_key="my special key"
    3. ... )

    The association proxy returns to us a collection of Keyword objects represented by all these operations:

    1. >>> print(user.keywords)
    2. [Keyword('new_from_blammo'), Keyword('its_big'), Keyword('its_heavy'), Keyword('its_wood')]

    Proxying to Dictionary Based Collections

    The association proxy can proxy to dictionary based collections as well. SQLAlchemy mappings usually use the attribute_keyed_dict() collection type to create dictionary collections, as well as the extended techniques described in .

    The association proxy adjusts its behavior when it detects the usage of a dictionary-based collection. When new values are added to the dictionary, the association proxy instantiates the intermediary object by passing two arguments to the creation function instead of one, the key and the value. As always, this creation function defaults to the constructor of the intermediary class, and can be customized using the creator argument.

    Below, we modify our UserKeywordAssociation example such that the User.user_keyword_associations collection will now be mapped using a dictionary, where the UserKeywordAssociation.special_key argument will be used as the key for the dictionary. We also apply a creator argument to the User.keywords proxy so that these values are assigned appropriately when new elements are added to the dictionary:

    1. from __future__ import annotations
    2. from sqlalchemy import ForeignKey
    3. from sqlalchemy import String
    4. from sqlalchemy.ext.associationproxy import association_proxy
    5. from sqlalchemy.ext.associationproxy import AssociationProxy
    6. from sqlalchemy.orm import DeclarativeBase
    7. from sqlalchemy.orm import Mapped
    8. from sqlalchemy.orm import mapped_column
    9. from sqlalchemy.orm import relationship
    10. from sqlalchemy.orm.collections import attribute_keyed_dict
    11. class Base(DeclarativeBase):
    12. pass
    13. class User(Base):
    14. __tablename__ = "user"
    15. id: Mapped[int] = mapped_column(primary_key=True)
    16. name: Mapped[str] = mapped_column(String(64))
    17. # user/user_keyword_associations relationship, mapping
    18. # user_keyword_associations with a dictionary against "special_key" as key.
    19. user_keyword_associations: Mapped[dict[str, UserKeywordAssociation]] = relationship(
    20. back_populates="user",
    21. collection_class=attribute_keyed_dict("special_key"),
    22. cascade="all, delete-orphan",
    23. )
    24. # proxy to 'user_keyword_associations', instantiating
    25. # UserKeywordAssociation assigning the new key to 'special_key',
    26. # values to 'keyword'.
    27. keywords: AssociationProxy[dict[str, Keyword]] = association_proxy(
    28. "user_keyword_associations",
    29. "keyword",
    30. creator=lambda k, v: UserKeywordAssociation(special_key=k, keyword=v),
    31. )
    32. def __init__(self, name: str):
    33. self.name = name
    34. class UserKeywordAssociation(Base):
    35. __tablename__ = "user_keyword"
    36. user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), primary_key=True)
    37. keyword_id: Mapped[int] = mapped_column(ForeignKey("keyword.id"), primary_key=True)
    38. special_key: Mapped[str]
    39. user: Mapped[User] = relationship(
    40. back_populates="user_keyword_associations",
    41. )
    42. keyword: Mapped[Keyword] = relationship()
    43. class Keyword(Base):
    44. __tablename__ = "keyword"
    45. id: Mapped[int] = mapped_column(primary_key=True)
    46. keyword: Mapped[str] = mapped_column(String(64))
    47. def __init__(self, keyword: str):
    48. self.keyword = keyword
    49. def __repr__(self) -> str:
    50. return f"Keyword({self.keyword!r})"

    We illustrate the .keywords collection as a dictionary, mapping the UserKeywordAssociation.special_key value to Keyword objects:

    1. >>> user = User("log")
    2. >>> user.keywords["sk1"] = Keyword("kw1")
    3. >>> user.keywords["sk2"] = Keyword("kw2")
    4. >>> print(user.keywords)
    5. {'sk1': Keyword('kw1'), 'sk2': Keyword('kw2')}

    Given our previous examples of proxying from relationship to scalar attribute, proxying across an association object, and proxying dictionaries, we can combine all three techniques together to give User a keywords dictionary that deals strictly with the string value of special_key mapped to the string keyword. Both the UserKeywordAssociation and Keyword classes are entirely concealed. This is achieved by building an association proxy on User that refers to an association proxy present on UserKeywordAssociation:

    1. from __future__ import annotations
    2. from sqlalchemy import ForeignKey
    3. from sqlalchemy import String
    4. from sqlalchemy.ext.associationproxy import association_proxy
    5. from sqlalchemy.ext.associationproxy import AssociationProxy
    6. from sqlalchemy.orm import DeclarativeBase
    7. from sqlalchemy.orm import Mapped
    8. from sqlalchemy.orm import mapped_column
    9. from sqlalchemy.orm import relationship
    10. from sqlalchemy.orm.collections import attribute_keyed_dict
    11. class Base(DeclarativeBase):
    12. pass
    13. class User(Base):
    14. __tablename__ = "user"
    15. id: Mapped[int] = mapped_column(primary_key=True)
    16. name: Mapped[str] = mapped_column(String(64))
    17. user_keyword_associations: Mapped[dict[str, UserKeywordAssociation]] = relationship(
    18. back_populates="user",
    19. collection_class=attribute_keyed_dict("special_key"),
    20. cascade="all, delete-orphan",
    21. )
    22. # the same 'user_keyword_associations'->'keyword' proxy as in
    23. # the basic dictionary example.
    24. keywords: AssociationProxy[dict[str, str]] = association_proxy(
    25. "user_keyword_associations",
    26. "keyword",
    27. creator=lambda k, v: UserKeywordAssociation(special_key=k, keyword=v),
    28. )
    29. def __init__(self, name: str):
    30. self.name = name
    31. class UserKeywordAssociation(Base):
    32. __tablename__ = "user_keyword"
    33. user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), primary_key=True)
    34. keyword_id: Mapped[int] = mapped_column(ForeignKey("keyword.id"), primary_key=True)
    35. special_key: Mapped[str] = mapped_column(String(64))
    36. user: Mapped[User] = relationship(
    37. back_populates="user_keyword_associations",
    38. )
    39. # the relationship to Keyword is now called
    40. # 'kw'
    41. kw: Mapped[Keyword] = relationship()
    42. # 'keyword' is changed to be a proxy to the
    43. # 'keyword' attribute of 'Keyword'
    44. keyword: AssociationProxy[dict[str, str]] = association_proxy("kw", "keyword")
    45. class Keyword(Base):
    46. __tablename__ = "keyword"
    47. id: Mapped[int] = mapped_column(primary_key=True)
    48. keyword: Mapped[str] = mapped_column(String(64))
    49. def __init__(self, keyword: str):
    50. self.keyword = keyword

    User.keywords is now a dictionary of string to string, where UserKeywordAssociation and Keyword objects are created and removed for us transparently using the association proxy. In the example below, we illustrate usage of the assignment operator, also appropriately handled by the association proxy, to apply a dictionary value to the collection at once:

    1. >>> user = User("log")
    2. >>> user.keywords = {"sk1": "kw1", "sk2": "kw2"}
    3. >>> print(user.keywords)
    4. {'sk1': 'kw1', 'sk2': 'kw2'}
    5. >>> user.keywords["sk3"] = "kw3"
    6. >>> del user.keywords["sk2"]
    7. >>> print(user.keywords)
    8. {'sk1': 'kw1', 'sk3': 'kw3'}
    9. >>> # illustrate un-proxied usage
    10. ... print(user.user_keyword_associations["sk3"].kw)
    11. <__main__.Keyword object at 0x12ceb90>

    One caveat with our example above is that because Keyword objects are created for each dictionary set operation, the example fails to maintain uniqueness for the Keyword objects on their string name, which is a typical requirement for a tagging scenario such as this one. For this use case the recipe , or a comparable creational strategy, is recommended, which will apply a “lookup first, then create” strategy to the constructor of the Keyword class, so that an already existing Keyword is returned if the given name is already present.

    Querying with Association Proxies

    The features simple SQL construction capabilities which work at the class level in a similar way as other ORM-mapped attributes, and provide rudimentary filtering support primarily based on the SQL EXISTS keyword.

    Note

    The primary purpose of the association proxy extension is to allow for improved persistence and object-access patterns with mapped object instances that are already loaded. The class-bound querying feature is of limited use and will not replace the need to refer to the underlying attributes when constructing SQL queries with JOINs, eager loading options, etc.

    For this section, assume a class with both an association proxy that refers to a column, as well as an association proxy that refers to a related object, as in the example mapping below:

    1. from __future__ import annotations
    2. from sqlalchemy import Column, ForeignKey, Integer, String
    3. from sqlalchemy.ext.associationproxy import association_proxy, AssociationProxy
    4. from sqlalchemy.orm import DeclarativeBase, relationship
    5. from sqlalchemy.orm.collections import attribute_keyed_dict
    6. from sqlalchemy.orm.collections import Mapped
    7. class Base(DeclarativeBase):
    8. pass
    9. class User(Base):
    10. __tablename__ = "user"
    11. id: Mapped[int] = mapped_column(primary_key=True)
    12. name: Mapped[str] = mapped_column(String(64))
    13. user_keyword_associations: Mapped[UserKeywordAssociation] = relationship(
    14. cascade="all, delete-orphan",
    15. )
    16. # object-targeted association proxy
    17. keywords: AssociationProxy[List[Keyword]] = association_proxy(
    18. "user_keyword_associations",
    19. "keyword",
    20. )
    21. # column-targeted association proxy
    22. special_keys: AssociationProxy[list[str]] = association_proxy(
    23. "user_keyword_associations", "special_key"
    24. )
    25. class UserKeywordAssociation(Base):
    26. __tablename__ = "user_keyword"
    27. user_id: Mapped[int] = mapped_column(ForeignKey("user.id"), primary_key=True)
    28. keyword_id: Mapped[int] = mapped_column(ForeignKey("keyword.id"), primary_key=True)
    29. special_key: Mapped[str] = mapped_column(String(64))
    30. keyword: Mapped[Keyword] = relationship()
    31. class Keyword(Base):
    32. __tablename__ = "keyword"
    33. id: Mapped[int] = mapped_column(primary_key=True)
    34. keyword: Mapped[str] = mapped_column(String(64))

    The SQL generated takes the form of a correlated subquery against the EXISTS SQL operator so that it can be used in a WHERE clause without the need for additional modifications to the enclosing query. If the immediate target of an association proxy is a mapped column expression, standard column operators can be used which will be embedded in the subquery. For example a straight equality operator:

    1. >>> print(session.scalars(select(User).where(User.special_keys == "jek")))
    2. SELECT "user".id AS user_id, "user".name AS user_name
    3. FROM "user"
    4. WHERE EXISTS (SELECT 1
    5. FROM user_keyword
    6. WHERE "user".id = user_keyword.user_id AND user_keyword.special_key = :special_key_1)

    a LIKE operator:

    1. >>> print(session.scalars(select(User).where(User.special_keys.like("%jek"))))
    2. SELECT "user".id AS user_id, "user".name AS user_name
    3. FROM "user"
    4. WHERE EXISTS (SELECT 1
    5. FROM user_keyword
    6. WHERE "user".id = user_keyword.user_id AND user_keyword.special_key LIKE :special_key_1)

    For association proxies where the immediate target is a related object or collection, or another association proxy or attribute on the related object, relationship-oriented operators can be used instead, such as PropComparator.has() and . The User.keywords attribute is in fact two association proxies linked together, so when using this proxy for generating SQL phrases, we get two levels of EXISTS subqueries:

    1. >>> print(session.scalars(select(User).where(User.keywords.any(Keyword.keyword == "jek"))))
    2. SELECT "user".id AS user_id, "user".name AS user_name
    3. FROM "user"
    4. WHERE EXISTS (SELECT 1
    5. FROM user_keyword
    6. WHERE "user".id = user_keyword.user_id AND (EXISTS (SELECT 1
    7. FROM keyword
    8. WHERE keyword.id = user_keyword.keyword_id AND keyword.keyword = :keyword_1)))

    This is not the most efficient form of SQL, so while association proxies can be convenient for generating WHERE criteria quickly, SQL results should be inspected and “unrolled” into explicit JOIN criteria for best use, especially when chaining association proxies together.

    Changed in version 1.3: Association proxy features distinct querying modes based on the type of target. See AssociationProxy now provides standard column operators for a column-oriented target.

    New in version 1.3.

    Given a mapping as:

    1. from __future__ import annotations
    2. from sqlalchemy import Column, ForeignKey, Integer, String
    3. from sqlalchemy.ext.associationproxy import association_proxy, AssociationProxy
    4. from sqlalchemy.orm import DeclarativeBase, relationship
    5. from sqlalchemy.orm.collections import attribute_keyed_dict
    6. from sqlalchemy.orm.collections import Mapped
    7. class Base(DeclarativeBase):
    8. pass
    9. class A(Base):
    10. __tablename__ = "test_a"
    11. id: Mapped[int] = mapped_column(primary_key=True)
    12. ab: Mapped[AB] = relationship(uselist=False)
    13. b: AssociationProxy[B] = association_proxy(
    14. "ab", "b", creator=lambda b: AB(b=b), cascade_scalar_deletes=True
    15. )
    16. class B(Base):
    17. __tablename__ = "test_b"
    18. id: Mapped[int] = mapped_column(primary_key=True)
    19. class AB(Base):
    20. __tablename__ = "test_ab"
    21. a_id: Mapped[int] = mapped_column(ForeignKey(A.id), primary_key=True)
    22. b_id: Mapped[int] = mapped_column(ForeignKey(B.id), primary_key=True)
    23. b: Mapped[B] = relationship()

    An assignment to A.b will generate an AB object:

    1. a.b = B()

    The A.b association is scalar, and includes use of the parameter AssociationProxy.cascade_scalar_deletes. When this parameter is enabled, setting A.b to None will remove A.ab as well:

    1. a.b = None
    2. assert a.ab is None

    When is not set, the association object a.ab above would remain in place.

    Note that this is not the behavior for collection-based association proxies; in that case, the intermediary association object is always removed when members of the proxied collection are removed. Whether or not the row is deleted depends on the relationship cascade setting.

    See also

    Cascades

    API Documentation

    function sqlalchemy.ext.associationproxy.association_proxy(target_collection: str, attr: str, *, creator: Optional[_CreatorProtocol] = None, getset_factory: Optional[_GetSetFactoryProtocol] = None, proxy_factory: Optional[_ProxyFactoryProtocol] = None, proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None, info: Optional[_InfoType] = None, cascade_scalar_deletes: bool = False, init: Union[_NoArg, bool] = _NoArg.NO_ARG, repr: Union[_NoArg, bool] = _NoArg.NO_ARG, default: Optional[Any] = _NoArg.NO_ARG, default_factory: Union[_NoArg, Callable[[], _T]] = _NoArg.NO_ARG, compare: Union[_NoArg, bool] = _NoArg.NO_ARG, kw_only: Union[_NoArg, bool] = _NoArg.NO_ARG) → AssociationProxy[Any]

    Return a Python property implementing a view of a target attribute which references an attribute on members of the target.

    The returned value is an instance of .

    Implements a Python property representing a relationship as a collection of simpler values, or a scalar value. The proxied property will mimic the collection type of the target (list, dict or set), or, in the case of a one to one relationship, a simple scalar value.

    • Parameters:

      • target_collection – Name of the attribute that is the immediate target. This attribute is typically mapped by relationship() to link to a target collection, but can also be a many-to-one or non-scalar relationship.

      • attr – Attribute on the associated instance or instances that are available on instances of the target object.

      • creator

        optional.

        Defines custom behavior when new items are added to the proxied collection.

        By default, adding new items to the collection will trigger a construction of an instance of the target object, passing the given item as a positional argument to the target constructor. For cases where this isn’t sufficient, can supply a callable that will construct the object in the appropriate way, given the item that was passed.

        For list- and set- oriented collections, a single argument is passed to the callable. For dictionary oriented collections, two arguments are passed, corresponding to the key and value.

        The association_proxy.creator callable is also invoked for scalar (i.e. many-to-one, one-to-one) relationships. If the current value of the target relationship attribute is None, the callable is used to construct a new object. If an object value already exists, the given attribute value is populated onto that object.

        See also

      • cascade_scalar_deletes

        when True, indicates that setting the proxied value to None, or deleting it via del, should also remove the source object. Only applies to scalar attributes. Normally, removing the proxied target will not remove the proxy source, as this object may have other state that is still to be kept.

        New in version 1.3.

        See also

        Cascading Scalar Deletes - complete usage example

      • init

        Specific to , specifies if the mapped attribute should be part of the __init__() method as generated by the dataclass process.

        New in version 2.0.0b4.

      • repr

        Specific to Declarative Dataclass Mapping, specifies if the attribute established by this should be part of the __repr__() method as generated by the dataclass process.

        New in version 2.0.0b4.

      • default_factory

        Specific to Declarative Dataclass Mapping, specifies a default-value generation function that will take place as part of the __init__() method as generated by the dataclass process.

        New in version 2.0.0b4.

      • compare

        Specific to , indicates if this field should be included in comparison operations when generating the __eq__() and __ne__() methods for the mapped class.

        New in version 2.0.0b4.

      • kw_only

        Specific to Declarative Dataclass Mapping, indicates if this field should be marked as keyword-only when generating the __init__() method as generated by the dataclass process.

        New in version 2.0.0b4.

      • info – optional, will be assigned to if present.

    The following additional parameters involve injection of custom behaviors within the AssociationProxy object and are for advanced use only:

    • Parameters:

      • getset_factory

        Optional. Proxied attribute access is automatically handled by routines that get and set values based on the attr argument for this proxy.

        If you would like to customize this behavior, you may supply a getset_factory callable that produces a tuple of getter and setter functions. The factory is called with two arguments, the abstract type of the underlying collection and this proxy instance.

      • proxy_factory – Optional. The type of collection to emulate is determined by sniffing the target collection. If your collection type can’t be determined by duck typing or you’d like to use a different collection implementation, you may supply a factory function to produce those collections. Only applicable to non-scalar relationships.

      • proxy_bulk_set – Optional, use with proxy_factory.

    class sqlalchemy.ext.associationproxy.AssociationProxy

    A descriptor that presents a read/write view of an object attribute.

    Members

    , creator, , for_class(), , info, , is_attribute, , is_clause_element, , is_mapper, , is_selectable, , proxy_bulk_set, , target_collection,

    Class signature

    class sqlalchemy.ext.associationproxy.AssociationProxy (, sqlalchemy.orm.base.ORMDescriptor, sqlalchemy.orm._DCAttributeOptions, sqlalchemy.ext.associationproxy._AssociationProxyProtocol)

    • method sqlalchemy.ext.associationproxy.AssociationProxy.__init__(target_collection: str, attr: str, *, creator: Optional[_CreatorProtocol] = None, getset_factory: Optional[_GetSetFactoryProtocol] = None, proxy_factory: Optional[_ProxyFactoryProtocol] = None, proxy_bulk_set: Optional[_ProxyBulkSetProtocol] = None, info: Optional[_InfoType] = None, cascade_scalar_deletes: bool = False, attribute_options: Optional[_AttributeOptions] = None)

      Construct a new .

      The AssociationProxy object is typically constructed using the constructor function. See the description of association_proxy() for a description of all parameters.

    • attribute creator: Optional[_CreatorProtocol]

    • attribute sqlalchemy.ext.associationproxy.AssociationProxy.extension_type: = ‘ASSOCIATION_PROXY’

      The extension type, if any. Defaults to NotExtension.NOT_EXTENSION

      See also

      HybridExtensionType

    • method sqlalchemy.ext.associationproxy.AssociationProxy.for_class(class\: Type[Any], _obj: Optional[object] = None) → [_T]

      Return the internal state local to a specific mapped class.

      E.g., given a class User:

      1. class User(Base):
      2. # ...
      3. keywords = association_proxy('kws', 'keyword')

      If we access this AssociationProxy from , and we want to view the target class for this proxy as mapped by User:

      1. inspect(User).all_orm_descriptors["keywords"].for_class(User).target_class

      This returns an instance of AssociationProxyInstance that is specific to the User class. The object remains agnostic of its parent class.

      • Parameters:

        • class_ – the class that we are returning state for.

        • obj – optional, an instance of the class that is required if the attribute refers to a polymorphic target, e.g. where we have to look at the type of the actual destination object to get the complete path.

    1. New in version 1.3: - [AssociationProxy](#sqlalchemy.ext.associationproxy.AssociationProxy "sqlalchemy.ext.associationproxy.AssociationProxy") no longer stores any state specific to a particular parent class; the state is now stored in per-class [AssociationProxyInstance](#sqlalchemy.ext.associationproxy.AssociationProxyInstance "sqlalchemy.ext.associationproxy.AssociationProxyInstance") objects.

    class sqlalchemy.ext.associationproxy.AssociationProxyInstance

    A per-class object that serves class- and object-specific results.

    This is used by AssociationProxy when it is invoked in terms of a specific class or instance of a class, i.e. when it is used as a regular Python descriptor.

    When referring to the as a normal Python descriptor, the AssociationProxyInstance is the object that actually serves the information. Under normal circumstances, its presence is transparent:

    1. >>> User.keywords.scalar
    2. False

    In the special case that the object is being accessed directly, in order to get an explicit handle to the AssociationProxyInstance, use the method:

    1. proxy_state = inspect(User).all_orm_descriptors["keywords"].for_class(User)
    2. # view if proxy object is scalar or not
    3. >>> proxy_state.scalar
    4. False

    New in version 1.3.

    Members

    __eq__(), , __lt__(), , all_(), , any_(), , attr, , bool_op(), , collection_class, , contains(), , desc(), , endswith(), , get(), , icontains(), , ilike(), , info, , is_distinct_from(), , is_not_distinct_from(), , isnot_distinct_from(), , like(), , match(), , not_in(), , notilike(), , notlike(), , nulls_last(), , nullslast(), , operate(), , regexp_match(), , remote_attr, , scalar, , startswith(), , timetuple

    Class signature

    class (sqlalchemy.orm.base.SQLORMOperations)

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.__eq__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__eq__ method of ColumnOperators

      Implement the == operator.

      In a column context, produces the clause a = b. If the target is None, produces a IS NULL.

    • method __le__(other: Any) → ColumnOperators

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__le__ method of

      Implement the <= operator.

      In a column context, produces the clause a <= b.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.__lt__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__lt__ method of ColumnOperators

      Implement the < operator.

      In a column context, produces the clause a < b.

    • method __ne__(other: Any) → ColumnOperators

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__ne__ method of

      Implement the != operator.

      In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.all_() →

      inherited from the ColumnOperators.all_() method of

      Produce an all_() clause against the parent object.

      See the documentation for for examples.

      Note

      be sure to not confuse the newer ColumnOperators.all_() method with its older -specific counterpart, the Comparator.all() method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method any(criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any) → ColumnElement[bool]

      Produce a proxied ‘any’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any() and/or Comparator.has() operators of the underlying proxied attributes.

    • method any_() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce an clause against the parent object.

      See the documentation for any_() for examples.

      Note

      be sure to not confuse the newer method with its older ARRAY-specific counterpart, the method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.asc() →

      inherited from the ColumnOperators.asc() method of

      Produce a asc() clause against the parent object.

    • attribute attr

      Return a tuple of (local_attr, remote_attr).

      This attribute was originally intended to facilitate using the Query.join() method to join across the two relationships at once, however this makes use of a deprecated calling style.

      To use select.join() or with an association proxy, the current method is to make use of the AssociationProxyInstance.local_attr and attributes separately:

      1. stmt = (
      2. join(Parent.proxied.local_attr).
      3. join(Parent.proxied.remote_attr)
      4. )

      A future release may seek to provide a more succinct join pattern for association proxy attributes.

      See also

      AssociationProxyInstance.local_attr

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.between(cleft: Any, cright: Any, symmetric: bool = False) →

      inherited from the ColumnOperators.between() method of

      Produce a between() clause against the parent object, given the lower and upper range.

    • method bool_op(opstring: str, precedence: int = 0, python_impl: Optional[Callable[[…], Any]] = None) → Callable[[Any], Operators]

      inherited from the method of Operators

      Return a custom boolean operator.

      This method is shorthand for calling and passing the Operators.op.is_comparison flag with True. A key advantage to using is that when using column constructs, the “boolean” nature of the returned expression will be present for PEP 484 purposes.

      See also

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.collate(collation: str) →

      inherited from the ColumnOperators.collate() method of

      Produce a collate() clause against the parent object, given the collation string.

      See also

    • attribute sqlalchemy.ext.associationproxy.AssociationProxyInstance.collection_class: Optional[Type[Any]]

    • method concat(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘concat’ operator.

      In a column context, produces the clause a || b, or uses the concat() operator on MySQL.

    • method contains(other: Any, **kw: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘contains’ operator.

      Produces a LIKE expression that tests against a match for the middle of a string value:

      1. column LIKE '%' || <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.contains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.contains.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.contains("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.contains("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.contains.autoescape:

          1. somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method delete(obj: Any) → None

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.desc() →

      inherited from the ColumnOperators.desc() method of

      Produce a desc() clause against the parent object.

    • method distinct() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.endswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.endswith() method of

      Implement the ‘endswith’ operator.

      Produces a LIKE expression that tests against a match for the end of a string value:

      1. column LIKE '%' || <other>

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.endswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.endswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.endswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.endswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.endswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • classmethod sqlalchemy.ext.associationproxy.AssociationProxyInstance.for_proxy(parent: [_T], owning_class: Type[Any], parent_instance: Any) → AssociationProxyInstance[_T]

    • method get(obj: Any) → Union[_T, None, AssociationProxyInstance[_T]]

    • method has(criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any) → ColumnElement[bool]

      Produce a proxied ‘has’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any() and/or Comparator.has() operators of the underlying proxied attributes.

    • method icontains(other: Any, **kw: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the icontains operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the middle of a string value:

      1. lower(column) LIKE '%' || lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.icontains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.icontains.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.icontains.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.icontains("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.icontains("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.iendswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.iendswith() method of

      Implement the iendswith operator, e.g. case insensitive version of ColumnOperators.endswith().

      Produces a LIKE expression that tests against an insensitive match for the end of a string value:

      1. lower(column) LIKE '%' || lower(<other>)

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.iendswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.iendswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.iendswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.iendswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'

          The parameter may also be combined with ColumnOperators.iendswith.autoescape:

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    • method ilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ilike operator, e.g. case insensitive LIKE.

      In a column context, produces an expression either of the form:

      1. lower(a) LIKE lower(other)

      Or on backends that support the ILIKE operator:

      1. a ILIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.ilike("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.ilike("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method in_(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the in operator.

      In a column context, produces the clause column IN <other>.

      The given parameter other may be:

      • A list of literal values, e.g.:

        1. stmt.where(column.in_([1, 2, 3]))

        In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:

        1. WHERE COL IN (?, ?, ?)
      • A list of tuples may be provided if the comparison is against a containing multiple expressions:

        1. from sqlalchemy import tuple_
        2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
      • An empty list, e.g.:

        1. stmt.where(column.in_([]))

        In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:

        1. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.

      • A bound parameter, e.g. bindparam(), may be used if it includes the flag:

        1. stmt.where(column.in_(bindparam('value', expanding=True)))

        In this calling form, the expression renders a special non-SQL placeholder expression that looks like:

        1. WHERE COL IN ([EXPANDING_value])

        This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:

        1. connection.execute(stmt, {"value": [1, 2, 3]})

        The database would be passed a bound parameter for each value:

        1. WHERE COL IN (?, ?, ?)

        New in version 1.2: added “expanding” bound parameters

        If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:

        1. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        New in version 1.3: “expanding” bound parameters now support empty lists

      • a select() construct, which is usually a correlated scalar select:

        1. stmt.where(
        2. column.in_(
        3. select(othertable.c.y).
        4. where(table.c.x == othertable.c.x)
        5. )
        6. )

        In this calling form, renders as given:

        1. WHERE COL IN (SELECT othertable.y
        2. FROM othertable WHERE othertable.x = table.x)
      • Parameters:

        other – a list of literals, a select() construct, or a construct that includes the bindparam.expanding flag set to True.

    • attribute info

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.is_(other: Any) →

      inherited from the ColumnOperators.is_() method of

      Implement the IS operator.

      Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.

      See also

      ColumnOperators.is_not()

    • method is_distinct_from(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS DISTINCT FROM operator.

      Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.

      New in version 1.1.

    • method is_not(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.is_not_distinct_from(other: Any) →

      inherited from the ColumnOperators.is_not_distinct_from() method of

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.isnot(other: Any) →

      inherited from the ColumnOperators.isnot() method of

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.is_()

    • method isnot_distinct_from(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method istartswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the istartswith operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the start of a string value:

      1. lower(column) LIKE lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.istartswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.istartswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.istartswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.istartswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.istartswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.like(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.like() method of

      Implement the like operator.

      In a column context, produces the expression:

      1. a LIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.like("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

    1. See also
    2. [ColumnOperators.ilike()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • attribute sqlalchemy.ext.associationproxy.AssociationProxyInstance.local_attr

      The ‘local’ class attribute referenced by this .

      See also

      AssociationProxyInstance.attr

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.match(other: Any, **kwargs: Any) →

      inherited from the ColumnOperators.match() method of

      Implements a database-specific ‘match’ operator.

      ColumnOperators.match() attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:

      • PostgreSQL - renders x @@ plainto_tsquery(y)

      • MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)

        See also

        - MySQL specific construct with additional features.

      • Oracle - renders CONTAINS(x, y)

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.not_ilike(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.not_ilike() method of

      implement the NOT ILIKE operator.

      This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.not_in(other: Any) →

      inherited from the ColumnOperators.not_in() method of

      implement the NOT IN operator.

      This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The ColumnOperators.in_() and operators now produce a “static” expression for an empty IN sequence by default.

      See also

      ColumnOperators.in_()

    • method not_like(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT LIKE operator.

      This is equivalent to using negation with , i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.like()

    • method notilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT ILIKE operator.

      This is equivalent to using negation with , i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.ilike()

    • method notin_(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT IN operator.

      This is equivalent to using negation with , i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The create_engine.empty_in_strategy may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The and ColumnOperators.not_in() operators now produce a “static” expression for an empty IN sequence by default.

      See also

    • inherited from the ColumnOperators.notlike() method of

      implement the NOT LIKE operator.

      This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.nulls_first() →

      inherited from the ColumnOperators.nulls_first() method of

      Produce a nulls_first() clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method nulls_last() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.nullsfirst() →

      inherited from the ColumnOperators.nullsfirst() method of

      Produce a nulls_first() clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method nullslast() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[Union[Type[[Any]], TypeEngine[Any]]] = None, python_impl: Optional[Callable[…, Any]] = None) → Callable[[Any], ]

      inherited from the Operators.op() method of

      Produce a generic operator function.

      e.g.:

      1. somecolumn.op("*")(5)

      produces:

      1. somecolumn * 5

      This function can also be used to make bitwise operators explicit. For example:

      1. somecolumn.op('&')(0xff)

      is a bitwise AND of the value in somecolumn.

      • Parameters:

        • opstring – a string which will be output as the infix operator between this element and the expression passed to the generated function.

        • precedence

          precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of 0 is lower than all operators except for the comma (,) and AS operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.

          See also

          I’m using op() to generate a custom operator and my parenthesis are not coming out correctly - detailed description of how the SQLAlchemy SQL compiler renders parenthesis

        • is_comparison

          legacy; if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like ==, >, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          Using the is_comparison parameter is superseded by using the method instead; this more succinct operator sets this parameter automatically, but also provides correct PEP 484 typing support as the returned object will express a “boolean” datatype, i.e. BinaryExpression[bool].

        • return_type – a class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify Operators.op.is_comparison will resolve to , and those that do not will be of the same type as the left-hand operand.

        • python_impl

          an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM “evaluator” used to match objects in a session after a multi-row update or delete.

          e.g.:

          1. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')

          The operator for the above expression will also work for non-SQL left and right objects:

          1. >>> expr.operator(5, 10)
          2. 15

          New in version 2.0.

    1. See also
    2. [Operators.bool\_op()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.Operators.bool_op "sqlalchemy.sql.expression.Operators.bool_op")
    3. [Redefining and Creating New Operators]($e8ad009010586d59.md#types-operators)
    4. [Using custom operators in join conditions]($b68ea79e4b407a37.md#relationship-custom-operator)
    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.operate(op: OperatorType, *other: Any, **kwargs: Any) →

      inherited from the Operators.operate() method of

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding ColumnOperators to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as ColumnOperators.contains().

    • attribute parent: _AssociationProxyProtocol[_T]

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.regexp_match(pattern: Any, flags: Optional[str] = None) →

      inherited from the ColumnOperators.regexp_match() method of

      Implements a database-specific ‘regexp match’ operator.

      E.g.:

      1. stmt = select(table.c.some_column).where(
      2. table.c.some_column.regexp_match('^(b|c)')
      3. )

      ColumnOperators.regexp_match() attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are not backend agnostic.

      Examples include:

      • PostgreSQL - renders x ~ y or x !~ y when negated.

      • Oracle - renders REGEXP_LIKE(x, y)

      • SQLite - uses SQLite’s REGEXP placeholder operator and calls into the Python re.match() builtin.

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.

      Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag ‘i’ in PostgreSQL, the ignore case regexp match operator ~* or !~* will be used.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_replace()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method regexp_replace(pattern: Any, replacement: Any, flags: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implements a database-specific ‘regexp replace’ operator.

      E.g.:

      1. stmt = select(
      2. table.c.some_column.regexp_replace(
      3. 'b(..)',
      4. 'XY',
      5. flags='g'
      6. )
      7. )

      attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function REGEXP_REPLACE(). However, the specific regular expression syntax and flags available are not backend agnostic.

      Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • pattern – The replacement string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_match()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
    • attribute sqlalchemy.ext.associationproxy.AssociationProxyInstance.remote_attr

      The ‘remote’ class attribute referenced by this .

      See also

      AssociationProxyInstance.attr

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.reverse_operate(op: OperatorType, other: Any, **kwargs: Any) →

      inherited from the Operators.reverse_operate() method of

      Reverse operate on an argument.

      Usage is the same as operate().

    • attribute scalar

      Return True if this AssociationProxyInstance proxies a scalar relationship on the local side.

    • method set(obj: Any, values: _T) → None

    • method sqlalchemy.ext.associationproxy.AssociationProxyInstance.startswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.startswith() method of

      Implement the startswith operator.

      Produces a LIKE expression that tests against a match for the start of a string value:

      1. column LIKE <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.startswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.startswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.startswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.startswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.startswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    3. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")

    class sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance

    an that has an object as a target.

    Members

    __le__(), , all_(), , any_(), , attr, , bool_op(), , concat(), , desc(), , endswith(), , icontains(), , ilike(), , is_(), , is_not(), , isnot(), , istartswith(), , local_attr, , not_ilike(), , not_like(), , notin_(), , nulls_first(), , nullsfirst(), , op(), , regexp_match(), , remote_attr, , scalar, , target_class,

    Class signature

    class sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance ()

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.__le__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__le__ method of ColumnOperators

      Implement the <= operator.

      In a column context, produces the clause a <= b.

    • method __lt__(other: Any) → ColumnOperators

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__lt__ method of

      Implement the < operator.

      In a column context, produces the clause a < b.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.all_() →

      inherited from the ColumnOperators.all_() method of

      Produce an all_() clause against the parent object.

      See the documentation for for examples.

      Note

      be sure to not confuse the newer ColumnOperators.all_() method with its older -specific counterpart, the Comparator.all() method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method any(criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any) → ColumnElement[bool]

      inherited from the method of AssociationProxyInstance

      Produce a proxied ‘any’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any() and/or Comparator.has() operators of the underlying proxied attributes.

    • method any_() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce an clause against the parent object.

      See the documentation for any_() for examples.

      Note

      be sure to not confuse the newer method with its older ARRAY-specific counterpart, the method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.asc() →

      inherited from the ColumnOperators.asc() method of

      Produce a asc() clause against the parent object.

    • attribute attr

      inherited from the AssociationProxyInstance.attr attribute of

      Return a tuple of (local_attr, remote_attr).

      This attribute was originally intended to facilitate using the Query.join() method to join across the two relationships at once, however this makes use of a deprecated calling style.

      To use select.join() or with an association proxy, the current method is to make use of the AssociationProxyInstance.local_attr and attributes separately:

      1. stmt = (
      2. select(Parent).
      3. join(Parent.proxied.local_attr).
      4. join(Parent.proxied.remote_attr)
      5. )

      A future release may seek to provide a more succinct join pattern for association proxy attributes.

      See also

      AssociationProxyInstance.local_attr

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.between(cleft: Any, cright: Any, symmetric: bool = False) →

      inherited from the ColumnOperators.between() method of

      Produce a between() clause against the parent object, given the lower and upper range.

    • method bool_op(opstring: str, precedence: int = 0, python_impl: Optional[Callable[[…], Any]] = None) → Callable[[Any], Operators]

      inherited from the method of Operators

      Return a custom boolean operator.

      This method is shorthand for calling and passing the Operators.op.is_comparison flag with True. A key advantage to using is that when using column constructs, the “boolean” nature of the returned expression will be present for PEP 484 purposes.

      See also

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.collate(collation: str) →

      inherited from the ColumnOperators.collate() method of

      Produce a collate() clause against the parent object, given the collation string.

      See also

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.concat(other: Any) →

      inherited from the ColumnOperators.concat() method of

      Implement the ‘concat’ operator.

      In a column context, produces the clause a || b, or uses the concat() operator on MySQL.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.contains(other: Any, **kw: Any) → [bool]

      Produce a proxied ‘contains’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any(), Comparator.has(), and/or Comparator.contains() operators of the underlying proxied attributes.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.desc() →

      inherited from the ColumnOperators.desc() method of

      Produce a desc() clause against the parent object.

    • method distinct() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.endswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.endswith() method of

      Implement the ‘endswith’ operator.

      Produces a LIKE expression that tests against a match for the end of a string value:

      1. column LIKE '%' || <other>

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.endswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.endswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.endswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.endswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.endswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.has(criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any) → [bool]

      inherited from the AssociationProxyInstance.has() method of

      Produce a proxied ‘has’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any() and/or Comparator.has() operators of the underlying proxied attributes.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.icontains(other: Any, **kw: Any) →

      inherited from the ColumnOperators.icontains() method of

      Implement the icontains operator, e.g. case insensitive version of ColumnOperators.contains().

      Produces a LIKE expression that tests against an insensitive match for the middle of a string value:

      1. lower(column) LIKE '%' || lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.icontains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.icontains.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.icontains("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.icontains("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.contains.autoescape:

          1. somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    • method iendswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the iendswith operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the end of a string value:

      1. lower(column) LIKE '%' || lower(<other>)

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.iendswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.iendswith.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.iendswith.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.iendswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.iendswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.ilike(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.ilike() method of

      Implement the ilike operator, e.g. case insensitive LIKE.

      In a column context, produces an expression either of the form:

      1. lower(a) LIKE lower(other)

      Or on backends that support the ILIKE operator:

      1. a ILIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.ilike("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.ilike("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.in_(other: Any) →

      inherited from the ColumnOperators.in_() method of

      Implement the in operator.

      In a column context, produces the clause column IN <other>.

      The given parameter other may be:

      • A list of literal values, e.g.:

        1. stmt.where(column.in_([1, 2, 3]))

        In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:

        1. WHERE COL IN (?, ?, ?)
      • A list of tuples may be provided if the comparison is against a tuple_() containing multiple expressions:

        1. from sqlalchemy import tuple_
        2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
      • An empty list, e.g.:

        1. stmt.where(column.in_([]))

        In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:

        1. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.

      • A bound parameter, e.g. , may be used if it includes the bindparam.expanding flag:

        1. stmt.where(column.in_(bindparam('value', expanding=True)))

        In this calling form, the expression renders a special non-SQL placeholder expression that looks like:

        1. WHERE COL IN ([EXPANDING_value])

        This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:

        1. connection.execute(stmt, {"value": [1, 2, 3]})

        The database would be passed a bound parameter for each value:

        1. WHERE COL IN (?, ?, ?)

        New in version 1.2: added “expanding” bound parameters

        If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:

        1. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        New in version 1.3: “expanding” bound parameters now support empty lists

      • a construct, which is usually a correlated scalar select:

        1. stmt.where(
        2. column.in_(
        3. select(othertable.c.y).
        4. where(table.c.x == othertable.c.x)
        5. )
        6. )

        In this calling form, ColumnOperators.in_() renders as given:

        1. WHERE COL IN (SELECT othertable.y
        2. FROM othertable WHERE othertable.x = table.x)
      • Parameters:

        other – a list of literals, a construct, or a bindparam() construct that includes the flag set to True.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.is_(other: Any) →

      inherited from the ColumnOperators.is_() method of

      Implement the IS operator.

      Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.

      See also

      ColumnOperators.is_not()

    • method is_distinct_from(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS DISTINCT FROM operator.

      Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.

      New in version 1.1.

    • method is_not_distinct_from(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method isnot(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.isnot_distinct_from(other: Any) →

      inherited from the ColumnOperators.isnot_distinct_from() method of

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.istartswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.istartswith() method of

      Implement the istartswith operator, e.g. case insensitive version of ColumnOperators.startswith().

      Produces a LIKE expression that tests against an insensitive match for the start of a string value:

      1. lower(column) LIKE lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.istartswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.istartswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.istartswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.istartswith.autoescape:

          1. somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    • method like(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the like operator.

      In a column context, produces the expression:

      1. a LIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.like("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.like("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.ilike()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • attribute local_attr

      inherited from the AssociationProxyInstance.local_attr attribute of

      The ‘local’ class attribute referenced by this AssociationProxyInstance.

      See also

      AssociationProxyInstance.remote_attr

    • method match(other: Any, **kwargs: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implements a database-specific ‘match’ operator.

      attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:

      • PostgreSQL - renders x @@ plainto_tsquery(y)

      • MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)

        See also

        match - MySQL specific construct with additional features.

      • Oracle - renders CONTAINS(x, y)

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.

    • method not_ilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT ILIKE operator.

      This is equivalent to using negation with , i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.ilike()

    • method not_in(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT IN operator.

      This is equivalent to using negation with , i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The create_engine.empty_in_strategy may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The and ColumnOperators.not_in() operators now produce a “static” expression for an empty IN sequence by default.

      See also

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.not_like(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.not_like() method of

      implement the NOT LIKE operator.

      This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.notilike(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.notilike() method of

      implement the NOT ILIKE operator.

      This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.notin_(other: Any) →

      inherited from the ColumnOperators.notin_() method of

      implement the NOT IN operator.

      This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The ColumnOperators.in_() and operators now produce a “static” expression for an empty IN sequence by default.

      See also

      ColumnOperators.in_()

    • method notlike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT LIKE operator.

      This is equivalent to using negation with , i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.like()

    • method nulls_first() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.nulls_last() →

      inherited from the ColumnOperators.nulls_last() method of

      Produce a nulls_last() clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method nullsfirst() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.nullslast() →

      inherited from the ColumnOperators.nullslast() method of

      Produce a nulls_last() clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[Union[Type[TypeEngine[Any]], [Any]]] = None, python_impl: Optional[Callable[…, Any]] = None) → Callable[[Any], Operators]

      inherited from the method of Operators

      Produce a generic operator function.

      e.g.:

      1. somecolumn.op("*")(5)

      produces:

      1. somecolumn * 5

      This function can also be used to make bitwise operators explicit. For example:

      1. somecolumn.op('&')(0xff)

      is a bitwise AND of the value in somecolumn.

      • Parameters:

        • opstring – a string which will be output as the infix operator between this element and the expression passed to the generated function.

        • precedence

          precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of 0 is lower than all operators except for the comma (,) and AS operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.

          See also

          - detailed description of how the SQLAlchemy SQL compiler renders parenthesis

        • is_comparison

          legacy; if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like ==, >, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          Using the is_comparison parameter is superseded by using the Operators.bool_op() method instead; this more succinct operator sets this parameter automatically, but also provides correct typing support as the returned object will express a “boolean” datatype, i.e. BinaryExpression[bool].

        • return_type – a TypeEngine class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify will resolve to Boolean, and those that do not will be of the same type as the left-hand operand.

        • python_impl

          an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM “evaluator” used to match objects in a session after a multi-row update or delete.

          e.g.:

          1. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')

          The operator for the above expression will also work for non-SQL left and right objects:

          1. >>> expr.operator(5, 10)
          2. 15

          New in version 2.0.

    1. See also
    2. [Operators.bool\_op()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.Operators.bool_op "sqlalchemy.sql.expression.Operators.bool_op")
    3. [Redefining and Creating New Operators]($e8ad009010586d59.md#types-operators)
    4. [Using custom operators in join conditions]($b68ea79e4b407a37.md#relationship-custom-operator)
    • method operate(op: OperatorType, *other: Any, **kwargs: Any) → Operators

      inherited from the method of Operators

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as ColumnOperators.contains().

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.regexp_match(pattern: Any, flags: Optional[str] = None) →

      inherited from the ColumnOperators.regexp_match() method of

      Implements a database-specific ‘regexp match’ operator.

      E.g.:

      1. stmt = select(table.c.some_column).where(
      2. table.c.some_column.regexp_match('^(b|c)')
      3. )

      ColumnOperators.regexp_match() attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are not backend agnostic.

      Examples include:

      • PostgreSQL - renders x ~ y or x !~ y when negated.

      • Oracle - renders REGEXP_LIKE(x, y)

      • SQLite - uses SQLite’s REGEXP placeholder operator and calls into the Python re.match() builtin.

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.

      Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag ‘i’ in PostgreSQL, the ignore case regexp match operator ~* or !~* will be used.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_replace()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method regexp_replace(pattern: Any, replacement: Any, flags: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implements a database-specific ‘regexp replace’ operator.

      1. stmt = select(
      2. table.c.some_column.regexp_replace(
      3. 'b(..)',
      4. 'XY',
      5. flags='g'
      6. )
      7. )

      attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function REGEXP_REPLACE(). However, the specific regular expression syntax and flags available are not backend agnostic.

      Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • pattern – The replacement string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_match()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
    • attribute sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.remote_attr

      inherited from the attribute of AssociationProxyInstance

      The ‘remote’ class attribute referenced by this .

      See also

      AssociationProxyInstance.attr

    • method sqlalchemy.ext.associationproxy.ObjectAssociationProxyInstance.reverse_operate(op: OperatorType, other: Any, **kwargs: Any) →

      inherited from the Operators.reverse_operate() method of

      Reverse operate on an argument.

      Usage is the same as operate().

    • attribute scalar

      inherited from the AssociationProxyInstance.scalar attribute of

      Return True if this AssociationProxyInstance proxies a scalar relationship on the local side.

    • method startswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the startswith operator.

      Produces a LIKE expression that tests against a match for the start of a string value:

      1. column LIKE <other> || '%'

      E.g.:

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.startswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.startswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.startswith.autoescape:

          1. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    3. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • attribute target_class: Type[Any]

      The intermediary class handled by this AssociationProxyInstance.

      Intercepted append/set/assignment events will result in the generation of new instances of this class.

    • attribute timetuple: Literal[None] = None

      inherited from the ColumnOperators.timetuple attribute of

      Hack, allows datetime objects to be compared on the LHS.

    class sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance

    an AssociationProxyInstance that has a database column as a target.

    Members

    , __lt__(), , all_(), , any_(), , attr, , bool_op(), , concat(), , desc(), , endswith(), , icontains(), , ilike(), , is_(), , is_not(), , isnot(), , istartswith(), , local_attr, , not_ilike(), , not_like(), , notin_(), , nulls_first(), , nullsfirst(), , op(), , regexp_match(), , remote_attr, , scalar, , target_class,

    Class signature

    class sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance ()

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.__le__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__le__ method of ColumnOperators

      Implement the <= operator.

      In a column context, produces the clause a <= b.

    • method __lt__(other: Any) → ColumnOperators

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__lt__ method of

      Implement the < operator.

      In a column context, produces the clause a < b.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.__ne__(other: Any) →

      inherited from the sqlalchemy.sql.expression.ColumnOperators.__ne__ method of ColumnOperators

      Implement the != operator.

      In a column context, produces the clause a != b. If the target is None, produces a IS NOT NULL.

    • method all_() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce an clause against the parent object.

      See the documentation for all_() for examples.

      Note

      be sure to not confuse the newer method with its older ARRAY-specific counterpart, the method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.any(criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any) → [bool]

      inherited from the AssociationProxyInstance.any() method of

      Produce a proxied ‘any’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any() and/or Comparator.has() operators of the underlying proxied attributes.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.any_() →

      inherited from the ColumnOperators.any_() method of

      Produce an any_() clause against the parent object.

      See the documentation for for examples.

      Note

      be sure to not confuse the newer ColumnOperators.any_() method with its older -specific counterpart, the Comparator.any() method, which a different calling syntax and usage pattern.

      New in version 1.1.

    • method asc() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • attribute sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.attr

      inherited from the attribute of AssociationProxyInstance

      Return a tuple of (local_attr, remote_attr).

      This attribute was originally intended to facilitate using the method to join across the two relationships at once, however this makes use of a deprecated calling style.

      To use select.join() or Query.join() with an association proxy, the current method is to make use of the and AssociationProxyInstance.remote_attr attributes separately:

      1. stmt = (
      2. select(Parent).
      3. join(Parent.proxied.local_attr).
      4. join(Parent.proxied.remote_attr)
      5. )

      A future release may seek to provide a more succinct join pattern for association proxy attributes.

      See also

      AssociationProxyInstance.remote_attr

    • method between(cleft: Any, cright: Any, symmetric: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object, given the lower and upper range.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.bool_op(opstring: str, precedence: int = 0, python_impl: Optional[Callable[[…], Any]] = None) → Callable[[Any], ]

      inherited from the Operators.bool_op() method of

      Return a custom boolean operator.

      This method is shorthand for calling Operators.op() and passing the flag with True. A key advantage to using Operators.bool_op() is that when using column constructs, the “boolean” nature of the returned expression will be present for purposes.

      See also

      Operators.op()

    • method collate(collation: str) → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object, given the collation string.

      See also

      collate()

    • method concat(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘concat’ operator.

      In a column context, produces the clause a || b, or uses the concat() operator on MySQL.

    • method contains(other: Any, **kw: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘contains’ operator.

      Produces a LIKE expression that tests against a match for the middle of a string value:

      1. column LIKE '%' || <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.contains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.contains.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.contains("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.contains("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.contains.autoescape:

          1. somecolumn.contains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method desc() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.distinct() →

      inherited from the ColumnOperators.distinct() method of

      Produce a distinct() clause against the parent object.

    • method endswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ‘endswith’ operator.

      Produces a LIKE expression that tests against a match for the end of a string value:

      1. column LIKE '%' || <other>

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.endswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.endswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.endswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.endswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE '%' || :param ESCAPE '^'

          The parameter may also be combined with ColumnOperators.endswith.autoescape:

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method has(criterion: Optional[_ColumnExpressionArgument[bool]] = None, **kwargs: Any) → ColumnElement[bool]

      inherited from the method of AssociationProxyInstance

      Produce a proxied ‘has’ expression using EXISTS.

      This expression will be a composed product using the Comparator.any() and/or Comparator.has() operators of the underlying proxied attributes.

    • method icontains(other: Any, **kw: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the icontains operator, e.g. case insensitive version of .

      Produces a LIKE expression that tests against an insensitive match for the middle of a string value:

      1. lower(column) LIKE '%' || lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.icontains("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the ColumnOperators.icontains.autoescape flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the ColumnOperators.icontains.autoescape flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.icontains("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.icontains("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with :

          1. somecolumn.icontains("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.contains()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.iendswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.iendswith() method of

      Implement the iendswith operator, e.g. case insensitive version of ColumnOperators.endswith().

      Produces a LIKE expression that tests against an insensitive match for the end of a string value:

      1. lower(column) LIKE '%' || lower(<other>)

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.iendswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.iendswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.iendswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.iendswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE '%' || lower(:param) ESCAPE '^'

          The parameter may also be combined with ColumnOperators.iendswith.autoescape:

          1. somecolumn.endswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.endswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    • method ilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the ilike operator, e.g. case insensitive LIKE.

      In a column context, produces an expression either of the form:

      1. lower(a) LIKE lower(other)

      Or on backends that support the ILIKE operator:

      1. a ILIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.ilike("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.ilike("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.like()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method in_(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the in operator.

      In a column context, produces the clause column IN <other>.

      The given parameter other may be:

      • A list of literal values, e.g.:

        1. stmt.where(column.in_([1, 2, 3]))

        In this calling form, the list of items is converted to a set of bound parameters the same length as the list given:

        1. WHERE COL IN (?, ?, ?)
      • A list of tuples may be provided if the comparison is against a containing multiple expressions:

        1. from sqlalchemy import tuple_
        2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
      • An empty list, e.g.:

        1. stmt.where(column.in_([]))

        In this calling form, the expression renders an “empty set” expression. These expressions are tailored to individual backends and are generally trying to get an empty SELECT statement as a subquery. Such as on SQLite, the expression is:

        1. WHERE col IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        Changed in version 1.4: empty IN expressions now use an execution-time generated SELECT subquery in all cases.

      • A bound parameter, e.g. bindparam(), may be used if it includes the flag:

        1. stmt.where(column.in_(bindparam('value', expanding=True)))

        In this calling form, the expression renders a special non-SQL placeholder expression that looks like:

        1. WHERE COL IN ([EXPANDING_value])

        This placeholder expression is intercepted at statement execution time to be converted into the variable number of bound parameter form illustrated earlier. If the statement were executed as:

        1. connection.execute(stmt, {"value": [1, 2, 3]})

        The database would be passed a bound parameter for each value:

        1. WHERE COL IN (?, ?, ?)

        New in version 1.2: added “expanding” bound parameters

        If an empty list is passed, a special “empty list” expression, which is specific to the database in use, is rendered. On SQLite this would be:

        1. WHERE COL IN (SELECT 1 FROM (SELECT 1) WHERE 1!=1)

        New in version 1.3: “expanding” bound parameters now support empty lists

      • a select() construct, which is usually a correlated scalar select:

        1. stmt.where(
        2. column.in_(
        3. select(othertable.c.y).
        4. where(table.c.x == othertable.c.x)
        5. )
        6. )

        In this calling form, renders as given:

        1. WHERE COL IN (SELECT othertable.y
        2. FROM othertable WHERE othertable.x = table.x)
      • Parameters:

        other – a list of literals, a select() construct, or a construct that includes the bindparam.expanding flag set to True.

    • method is_(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS operator.

      Normally, IS is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS may be desirable if comparing to boolean values on certain platforms.

      See also

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.is_distinct_from(other: Any) →

      inherited from the ColumnOperators.is_distinct_from() method of

      Implement the IS DISTINCT FROM operator.

      Renders “a IS DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS NOT b”.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.is_not(other: Any) →

      inherited from the ColumnOperators.is_not() method of

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.is_()

    • method is_not_distinct_from(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method isnot(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the IS NOT operator.

      Normally, IS NOT is generated automatically when comparing to a value of None, which resolves to NULL. However, explicit usage of IS NOT may be desirable if comparing to boolean values on certain platforms.

      Changed in version 1.4: The is_not() operator is renamed from isnot() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.isnot_distinct_from(other: Any) →

      inherited from the ColumnOperators.isnot_distinct_from() method of

      Implement the IS NOT DISTINCT FROM operator.

      Renders “a IS NOT DISTINCT FROM b” on most platforms; on some such as SQLite may render “a IS b”.

      Changed in version 1.4: The is_not_distinct_from() operator is renamed from isnot_distinct_from() in previous releases. The previous name remains available for backwards compatibility.

      New in version 1.1.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.istartswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) →

      inherited from the ColumnOperators.istartswith() method of

      Implement the istartswith operator, e.g. case insensitive version of ColumnOperators.startswith().

      Produces a LIKE expression that tests against an insensitive match for the start of a string value:

      1. lower(column) LIKE lower(<other>) || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.istartswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.istartswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.istartswith("foo%bar", autoescape=True)

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.istartswith("foo/%bar", escape="^")

          Will render as:

          1. lower(somecolumn) LIKE lower(:param) || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.istartswith.autoescape:

          1. somecolumn.istartswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to "foo^%bar^^bat" before being passed to the database.

    1. See also
    2. [ColumnOperators.startswith()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    • method like(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the like operator.

      In a column context, produces the expression:

      1. a LIKE other

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.like("%foobar%"))
      • Parameters:

        • other – expression to be compared

        • escape

          optional escape character, renders the ESCAPE keyword, e.g.:

          1. somecolumn.like("foo/%bar", escape="/")
    1. See also
    2. [ColumnOperators.ilike()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • attribute local_attr

      inherited from the AssociationProxyInstance.local_attr attribute of

      The ‘local’ class attribute referenced by this AssociationProxyInstance.

      See also

      AssociationProxyInstance.remote_attr

    • method match(other: Any, **kwargs: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      Implements a database-specific ‘match’ operator.

      attempts to resolve to a MATCH-like function or operator provided by the backend. Examples include:

      • PostgreSQL - renders x @@ plainto_tsquery(y)

      • MySQL - renders MATCH (x) AGAINST (y IN BOOLEAN MODE)

        See also

        match - MySQL specific construct with additional features.

      • Oracle - renders CONTAINS(x, y)

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “MATCH”. This is compatible with SQLite, for example.

    • method not_ilike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT ILIKE operator.

      This is equivalent to using negation with , i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.ilike()

    • method not_in(other: Any) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT IN operator.

      This is equivalent to using negation with , i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The create_engine.empty_in_strategy may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The and ColumnOperators.not_in() operators now produce a “static” expression for an empty IN sequence by default.

      See also

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.not_like(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.not_like() method of

      implement the NOT LIKE operator.

      This is equivalent to using negation with ColumnOperators.like(), i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.notilike(other: Any, escape: Optional[str] = None) →

      inherited from the ColumnOperators.notilike() method of

      implement the NOT ILIKE operator.

      This is equivalent to using negation with ColumnOperators.ilike(), i.e. ~x.ilike(y).

      Changed in version 1.4: The not_ilike() operator is renamed from notilike() in previous releases. The previous name remains available for backwards compatibility.

      See also

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.notin_(other: Any) →

      inherited from the ColumnOperators.notin_() method of

      implement the NOT IN operator.

      This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

      In the case that other is an empty sequence, the compiler produces an “empty not in” expression. This defaults to the expression “1 = 1” to produce true in all cases. The may be used to alter this behavior.

      Changed in version 1.4: The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

      Changed in version 1.2: The ColumnOperators.in_() and operators now produce a “static” expression for an empty IN sequence by default.

      See also

      ColumnOperators.in_()

    • method notlike(other: Any, escape: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      implement the NOT LIKE operator.

      This is equivalent to using negation with , i.e. ~x.like(y).

      Changed in version 1.4: The not_like() operator is renamed from notlike() in previous releases. The previous name remains available for backwards compatibility.

      See also

      ColumnOperators.like()

    • method nulls_first() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.nulls_last() →

      inherited from the ColumnOperators.nulls_last() method of

      Produce a nulls_last() clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method nullsfirst() → ColumnOperators

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      Changed in version 1.4: The nulls_first() operator is renamed from nullsfirst() in previous releases. The previous name remains available for backwards compatibility.

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.nullslast() →

      inherited from the ColumnOperators.nullslast() method of

      Produce a nulls_last() clause against the parent object.

      Changed in version 1.4: The nulls_last() operator is renamed from nullslast() in previous releases. The previous name remains available for backwards compatibility.

    • method op(opstring: str, precedence: int = 0, is_comparison: bool = False, return_type: Optional[Union[Type[TypeEngine[Any]], [Any]]] = None, python_impl: Optional[Callable[…, Any]] = None) → Callable[[Any], Operators]

      inherited from the method of Operators

      Produce a generic operator function.

      e.g.:

      1. somecolumn.op("*")(5)

      produces:

      1. somecolumn * 5

      This function can also be used to make bitwise operators explicit. For example:

      1. somecolumn.op('&')(0xff)

      is a bitwise AND of the value in somecolumn.

      • Parameters:

        • opstring – a string which will be output as the infix operator between this element and the expression passed to the generated function.

        • precedence

          precedence which the database is expected to apply to the operator in SQL expressions. This integer value acts as a hint for the SQL compiler to know when explicit parenthesis should be rendered around a particular operation. A lower number will cause the expression to be parenthesized when applied against another operator with higher precedence. The default value of 0 is lower than all operators except for the comma (,) and AS operators. A value of 100 will be higher or equal to all operators, and -100 will be lower than or equal to all operators.

          See also

          - detailed description of how the SQLAlchemy SQL compiler renders parenthesis

        • is_comparison

          legacy; if True, the operator will be considered as a “comparison” operator, that is which evaluates to a boolean true/false value, like ==, >, etc. This flag is provided so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          Using the is_comparison parameter is superseded by using the Operators.bool_op() method instead; this more succinct operator sets this parameter automatically, but also provides correct typing support as the returned object will express a “boolean” datatype, i.e. BinaryExpression[bool].

        • return_type – a TypeEngine class or object that will force the return type of an expression produced by this operator to be of that type. By default, operators that specify will resolve to Boolean, and those that do not will be of the same type as the left-hand operand.

        • python_impl

          an optional Python function that can evaluate two Python values in the same way as this operator works when run on the database server. Useful for in-Python SQL expression evaluation functions, such as for ORM hybrid attributes, and the ORM “evaluator” used to match objects in a session after a multi-row update or delete.

          e.g.:

          1. >>> expr = column('x').op('+', python_impl=lambda a, b: a + b)('y')

          The operator for the above expression will also work for non-SQL left and right objects:

          1. >>> expr.operator(5, 10)
          2. 15

          New in version 2.0.

    1. See also
    2. [Operators.bool\_op()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.Operators.bool_op "sqlalchemy.sql.expression.Operators.bool_op")
    3. [Redefining and Creating New Operators]($e8ad009010586d59.md#types-operators)
    4. [Using custom operators in join conditions]($b68ea79e4b407a37.md#relationship-custom-operator)
    • method operate(op: OperatorType, *other: Any, **kwargs: Any) → ColumnElement[Any]

      Operate on an argument.

      This is the lowest level of operation, raises NotImplementedError by default.

      Overriding this on a subclass can allow common behavior to be applied to all operations. For example, overriding to apply func.lower() to the left and right side:

      1. class MyComparator(ColumnOperators):
      2. def operate(self, op, other, **kwargs):
      3. return op(func.lower(self), func.lower(other), **kwargs)
      • Parameters:

        • op – Operator callable.

        • *other – the ‘other’ side of the operation. Will be a single scalar for most operations.

        • **kwargs – modifiers. These may be passed by special operators such as ColumnOperators.contains().

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.regexp_match(pattern: Any, flags: Optional[str] = None) →

      inherited from the ColumnOperators.regexp_match() method of

      Implements a database-specific ‘regexp match’ operator.

      E.g.:

      1. stmt = select(table.c.some_column).where(
      2. table.c.some_column.regexp_match('^(b|c)')
      3. )

      ColumnOperators.regexp_match() attempts to resolve to a REGEXP-like function or operator provided by the backend, however the specific regular expression syntax and flags available are not backend agnostic.

      Examples include:

      • PostgreSQL - renders x ~ y or x !~ y when negated.

      • Oracle - renders REGEXP_LIKE(x, y)

      • SQLite - uses SQLite’s REGEXP placeholder operator and calls into the Python re.match() builtin.

      • other backends may provide special implementations.

      • Backends without any special implementation will emit the operator as “REGEXP” or “NOT REGEXP”. This is compatible with SQLite and MySQL, for example.

      Regular expression support is currently implemented for Oracle, PostgreSQL, MySQL and MariaDB. Partial support is available for SQLite. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern. When using the ignore case flag ‘i’ in PostgreSQL, the ignore case regexp match operator ~* or !~* will be used.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_replace()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method regexp_replace(pattern: Any, replacement: Any, flags: Optional[str] = None) → ColumnOperators

      inherited from the method of ColumnOperators

      Implements a database-specific ‘regexp replace’ operator.

      E.g.:

      1. stmt = select(
      2. table.c.some_column.regexp_replace(
      3. 'b(..)',
      4. 'XY',
      5. flags='g'
      6. )
      7. )

      attempts to resolve to a REGEXP_REPLACE-like function provided by the backend, that usually emit the function REGEXP_REPLACE(). However, the specific regular expression syntax and flags available are not backend agnostic.

      Regular expression replacement support is currently implemented for Oracle, PostgreSQL, MySQL 8 or greater and MariaDB. Support among third-party dialects may vary.

      • Parameters:

        • pattern – The regular expression pattern string or column clause.

        • pattern – The replacement string or column clause.

        • flags – Any regular expression string flags to apply. Flags tend to be backend specific. It can be a string or a column clause. Some backends, like PostgreSQL and MariaDB, may alternatively specify the flags as part of the pattern.

    1. New in version 1.4.
    2. See also
    3. [ColumnOperators.regexp\_match()]($aafca12b71ff5dd3.md#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
    • attribute sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.remote_attr

      inherited from the attribute of AssociationProxyInstance

      The ‘remote’ class attribute referenced by this .

      See also

      AssociationProxyInstance.attr

    • method sqlalchemy.ext.associationproxy.ColumnAssociationProxyInstance.reverse_operate(op: OperatorType, other: Any, **kwargs: Any) →

      inherited from the Operators.reverse_operate() method of

      Reverse operate on an argument.

      Usage is the same as operate().

    • attribute scalar

      inherited from the AssociationProxyInstance.scalar attribute of

      Return True if this AssociationProxyInstance proxies a scalar relationship on the local side.

    • method startswith(other: Any, escape: Optional[str] = None, autoescape: bool = False) → ColumnOperators

      inherited from the method of ColumnOperators

      Implement the startswith operator.

      Produces a LIKE expression that tests against a match for the start of a string value:

      1. column LIKE <other> || '%'

      E.g.:

      1. stmt = select(sometable).\
      2. where(sometable.c.column.startswith("foobar"))

      Since the operator uses LIKE, wildcard characters "%" and "_" that are present inside the <other> expression will behave like wildcards as well. For literal string values, the flag may be set to True to apply escaping to occurrences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

      • Parameters:

        • other – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the flag is set to True.

        • autoescape

          boolean; when True, establishes an escape character within the LIKE expression, then applies it to all occurrences of "%", "_" and the escape character itself within the comparison value, which is assumed to be a literal string and not a SQL expression.

          An expression such as:

          1. somecolumn.startswith("foo%bar", autoescape=True)

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '/'

          With the value of :param as "foo/%bar".

        • escape

          a character which when given will render with the ESCAPE keyword to establish that character as the escape character. This character can then be placed preceding occurrences of % and _ to allow them to act as themselves and not wildcard characters.

          An expression such as:

          1. somecolumn.startswith("foo/%bar", escape="^")

          Will render as:

          1. somecolumn LIKE :param || '%' ESCAPE '^'

          The parameter may also be combined with ColumnOperators.startswith.autoescape:

          1. somecolumn.startswith("foo%bar^bat", escape="^", autoescape=True)

          Where above, the given literal parameter will be converted to before being passed to the database.

    • attribute target_class: Type[Any]

      The intermediary class handled by this AssociationProxyInstance.

      Intercepted append/set/assignment events will result in the generation of new instances of this class.

    • attribute timetuple: Literal[None] = None

      inherited from the ColumnOperators.timetuple attribute of

      Hack, allows datetime objects to be compared on the LHS.

    class sqlalchemy.ext.associationproxy.AssociationProxyExtensionType

    An enumeration.

    Members

    ASSOCIATION_PROXY

    Class signature

    class (sqlalchemy.orm.base.InspectionAttrExtensionType)

    • attribute ASSOCIATION_PROXY = ‘ASSOCIATION_PROXY’

      Symbol indicating an InspectionAttr that’s of type .