ORM Internals

    class sqlalchemy.orm.``AttributeState(state, key)

    Provide an inspection interface corresponding to a particular attribute on a particular mapped object.

    The AttributeState object is accessed via the collection of a particular InstanceState:

    • attribute history

      Return the current pre-flush change history for this attribute, via the History interface.

      This method will not emit loader callables if the value of the attribute is unloaded.

      Note

      The attribute history system tracks changes on a per flush basis. Each time the is flushed, the history of each attribute is reset to empty. The Session by default autoflushes each time a is invoked. For options on how to control this, see Flushing.

      See also

      - retrieve history using loader callables if the value is not locally present.

      get_history() - underlying function

    • method load_history()

      Return the current pre-flush change history for this attribute, via the History interface.

      This method will emit loader callables if the value of the attribute is unloaded.

      Note

      The attribute history system tracks changes on a per flush basis. Each time the is flushed, the history of each attribute is reset to empty. The Session by default autoflushes each time a is invoked. For options on how to control this, see Flushing.

      See also

      get_history() - underlying function

      New in version 0.9.0.

    • attribute loaded_value

      The current value of this attribute as loaded from the database.

      If the value has not been loaded, or is otherwise not present in the object’s dictionary, returns NO_VALUE.

    • attribute sqlalchemy.orm.AttributeState.value

      Return the value of this attribute.

      This operation is equivalent to accessing the object’s attribute directly or via getattr(), and will fire off any pending loader callables if needed.

    class sqlalchemy.orm.``CascadeOptions(value_list)

    Keeps track of the options sent to

    Class signature

    class sqlalchemy.orm.CascadeOptions (builtins.frozenset)

    class sqlalchemy.orm.``ClassManager(class_)

    Tracks state information at the class level.

    Class signature

    class (sqlalchemy.util.langhelpers.HasMemoized, builtins.dict)

    • method sqlalchemy.orm.ClassManager.clear() → None. Remove all items from D.

      inherited from the builtins.dict.clear method of builtins.dict

    • method copy() → a shallow copy of D

      inherited from the builtins.dict.copy method of builtins.dict

    • attribute sqlalchemy.orm.ClassManager.deferred_scalar_loader

      Deprecated since version 1.4: The ClassManager.deferred_scalar_loader attribute is now named expired_attribute_loader

    • attribute expired_attribute_loader = None

      previously known as deferred_scalar_loader

    • method sqlalchemy.orm.ClassManager.fromkeys(value=None, /)

      inherited from the builtins.dict.fromkeys method of builtins.dict

      Create a new dictionary with keys from iterable and values set to value.

    • method get(key, default=None, /)

      inherited from the builtins.dict.get method of builtins.dict

      Return the value for key if key is in the dictionary, else default.

    • method sqlalchemy.orm.ClassManager.has_parent(state, key, optimistic=False)

      TODO

    • method items() → a set-like object providing a view on D’s items

      inherited from the builtins.dict.items method of builtins.dict

    • method sqlalchemy.orm.ClassManager.keys() → a set-like object providing a view on D’s keys

      inherited from the builtins.dict.keys method of builtins.dict

    • method manage()

      Mark this instance as the manager for its class.

    • class memoized_attribute(fget, doc=None)

      A read-only @property that is only evaluated once.

    • method sqlalchemy.orm.ClassManager.classmethod memoized_instancemethod(fn)

      inherited from the HasMemoized.memoized_instancemethod() method of HasMemoized

      Decorate a method memoize its return value.

    • method pop(k[, d]) → v, remove specified key and return the corresponding value.

      inherited from the builtins.dict.pop method of builtins.dict

      If key is not found, d is returned if given, otherwise KeyError is raised

    • method sqlalchemy.orm.ClassManager.popitem() → (k, v), remove and return some (key, value) pair as a

      inherited from the builtins.dict.popitem method of builtins.dict

      2-tuple; but raise KeyError if D is empty.

    • method setdefault(key, default=None, /)

      inherited from the builtins.dict.setdefault method of builtins.dict

      Insert key with a value of default if key is not in the dictionary.

      Return the value for key if key is in the dictionary, else default.

    • method sqlalchemy.orm.ClassManager.state_getter()

      Return a (instance) -> InstanceState callable.

      “state getter” callables should raise either KeyError or AttributeError if no InstanceState could be found for the instance.

    • method unregister()

      remove all instrumentation established by this ClassManager.

    • method sqlalchemy.orm.ClassManager.update([E, ]\*F*) → None. Update D from dict/iterable E and F.

      inherited from the builtins.dict.update method of builtins.dict

      If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]

    • method values() → an object providing a view on D’s values

      inherited from the builtins.dict.values method of builtins.dict

    class sqlalchemy.orm.``ColumnProperty(\columns, **kwargs*)

    Describes an object attribute that corresponds to a table column.

    Public constructor is the column_property() function.

    Class signature

    class (sqlalchemy.orm.StrategizedProperty)

    • attribute sqlalchemy.orm.ColumnProperty.Comparator.``expressions

      The full sequence of columns referenced by this attribute, adjusted for any aliasing in progress.

      New in version 1.3.17.

      See also

      - usage example

    • class Comparator(prop, parentmapper, adapt_to_entity=None)

      Produce boolean, comparison, and other operators for ColumnProperty attributes.

      See the documentation for for a brief overview.

      See also

      PropComparator

      Redefining and Creating New Operators

      Class signature

      class sqlalchemy.orm.ColumnProperty.Comparator (sqlalchemy.util.langhelpers.MemoizedSlots, )

      • method sqlalchemy.orm.ColumnProperty.Comparator.operate(op, \other, **kwargs*)

        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):
        3. return op(func.lower(self), func.lower(other))

        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.orm.ColumnProperty.Comparator.reverse_operate(op, other, \*kwargs*)

        Reverse operate on an argument.

        Usage is the same as .

    • method sqlalchemy.orm.ColumnProperty.__init__(\columns, **kwargs*)

      Construct a new object.

      This constructor is mirrored as a public API function; see sqlalchemy.orm.column_property() for a full usage and argument description.

    • method do_init()

      Perform subclass-specific initialization post-mapper-creation steps.

      This is a template method called by the MapperProperty object’s init() method.

    • attribute sqlalchemy.orm.ColumnProperty.expression

      Return the primary column or expression for this ColumnProperty.

      E.g.:

      1. class File(Base):
      2. # ...
      3. name = Column(String(64))
      4. extension = Column(String(8))
      5. filename = column_property(name + '.' + extension)
      6. path = column_property('C:/' + filename.expression)

      See also

    • method sqlalchemy.orm.ColumnProperty.instrument_class(mapper)

      Hook called by the Mapper to the property to initiate instrumentation of the class attribute managed by this MapperProperty.

      The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAttribute.

      This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mapper setup process.

      The second step is typically the init_class_attribute step, called from StrategizedProperty via the post_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specifically the “impl”) which has been determined after the MapperProperty has determined what kind of persistence management it needs to do (e.g. scalar, object, collection, etc).

    • method merge(session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map)

      Merge the attribute represented by this MapperProperty from source to destination object.

    class sqlalchemy.orm.``CompositeProperty(class_, \attrs, **kwargs*)

    Defines a “composite” mapped attribute, representing a collection of columns as one attribute.

    CompositeProperty is constructed using the function.

    See also

    Composite Column Types

    Class signature

    class (sqlalchemy.orm.descriptor_props.DescriptorProperty)

    • class Comparator(prop, parentmapper, adapt_to_entity=None)

      Produce boolean, comparison, and other operators for CompositeProperty attributes.

      See the example in for an overview of usage , as well as the documentation for PropComparator.

      See also

      ColumnOperators

      TypeEngine.comparator_factory

      Class signature

      class (sqlalchemy.orm.PropComparator)

    • class CompositeBundle(property_, expr)

      Class signature

      class (sqlalchemy.orm.Bundle)

      • method create_row_processor(query, procs, labels)

        Produce the “row processing” function for this Bundle.

        May be overridden by subclasses.

        See also

        - includes an example of subclassing.

    • method sqlalchemy.orm.CompositeProperty.__init__(class_, \attrs, **kwargs*)

      Construct a new object.

      This constructor is mirrored as a public API function; see sqlalchemy.orm.composite() for a full usage and argument description.

    • method do_init()

      Initialization which occurs after the CompositeProperty has been associated with its parent mapper.

    • method get_history(state, dict_, passive=symbol(‘PASSIVE_OFF’))

      Provided for userland code that uses attributes.get_history().

    • method sqlalchemy.orm.CompositeProperty.instrument_class(mapper)

      Hook called by the Mapper to the property to initiate instrumentation of the class attribute managed by this MapperProperty.

      The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAttribute.

      This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mapper setup process.

      The second step is typically the init_class_attribute step, called from StrategizedProperty via the post_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specifically the “impl”) which has been determined after the MapperProperty has determined what kind of persistence management it needs to do (e.g. scalar, object, collection, etc).

    class sqlalchemy.orm.``AttributeEvent(attribute_impl, op)

    A token propagated throughout the course of a chain of attribute events.

    Serves as an indicator of the source of the event and also provides a means of controlling propagation across a chain of attribute operations.

    The Event object is sent as the initiator argument when dealing with events such as , AttributeEvents.set(), and .

    The Event object is currently interpreted by the backref event handlers, and is used to control the propagation of operations across two mutually-dependent attributes.

    New in version 0.9.0.

    • Attribute impl

      The AttributeImpl which is the current event initiator.

      Attribute op

      The symbol OP_APPEND, OP_REMOVE, OP_REPLACE, or OP_BULK_REPLACE, indicating the source operation.

    class sqlalchemy.orm.``IdentityMap

    class sqlalchemy.orm.``InspectionAttr

    A base class applied to all ORM objects that can be returned by the function.

    The attributes defined here allow the usage of simple boolean checks to test basic facts about the object returned.

    While the boolean checks here are basically the same as using the Python isinstance() function, the flags here can be used without the need to import all of these classes, and also such that the SQLAlchemy class system can change while leaving the flags here intact for forwards-compatibility.

    class sqlalchemy.orm.``InspectionAttrInfo

    Adds the .info attribute to InspectionAttr.

    The rationale for vs. InspectionAttrInfo is that the former is compatible as a mixin for classes that specify __slots__; this is essentially an implementation artifact.

    Class signature

    class (sqlalchemy.orm.base.InspectionAttr)

    • attribute sqlalchemy.orm.InspectionAttrInfo.info

      Info dictionary associated with the object, allowing user-defined data to be associated with this .

      The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the column_property(), , or composite() functions.

      Changed in version 1.0.0: is also available on extension types via the InspectionAttrInfo.info attribute, so that it can apply to a wider variety of ORM and extension constructs.

      See also

      SchemaItem.info

    class sqlalchemy.orm.``InstanceState(obj, manager)

    tracks state information at the instance level.

    The is a key object used by the SQLAlchemy ORM in order to track the state of an object; it is created the moment an object is instantiated, typically as a result of instrumentation which SQLAlchemy applies to the __init__() method of the class.

    is also a semi-public object, available for runtime inspection as to the state of a mapped instance, including information such as its current status within a particular Session and details about data on individual attributes. The public API in order to acquire a object is to use the inspect() system:

    1. >>> from sqlalchemy import inspect
    2. >>> insp = inspect(some_mapped_object)

    See also

    Class signature

    class sqlalchemy.orm.InstanceState (sqlalchemy.orm.base.InspectionAttrInfo)

    • attribute attrs

      Return a namespace representing each attribute on the mapped object, including its current value and history.

      The returned object is an instance of AttributeState. This object allows inspection of the current data within an attribute as well as attribute history since the last flush.

    • attribute callables = ()

      A namespace where a per-state loader callable can be associated.

      In SQLAlchemy 1.0, this is only used for lazy loaders / deferred loaders that were set up via query option.

      Previously, callables was used also to indicate expired attributes by storing a link to the InstanceState itself in this dictionary. This role is now handled by the expired_attributes set.

    • attribute sqlalchemy.orm.InstanceState.deleted

      Return True if the object is .

      An object that is in the deleted state is guaranteed to not be within the Session.identity_map of its parent ; however if the session’s transaction is rolled back, the object will be restored to the persistent state and the identity map.

      Note

      The InstanceState.deleted attribute refers to a specific state of the object that occurs between the “persistent” and “detached” states; once the object is , the InstanceState.deleted attribute no longer returns True; in order to detect that a state was deleted, regardless of whether or not the object is associated with a , use the InstanceState.was_deleted accessor.

      See also

    • attribute sqlalchemy.orm.InstanceState.detached

      Return True if the object is .

      See also

      Quickie Intro to Object States

    • attribute dict

      Return the instance dict used by the object.

      Under normal circumstances, this is always synonymous with the __dict__ attribute of the mapped object, unless an alternative instrumentation system has been configured.

      In the case that the actual object has been garbage collected, this accessor returns a blank dictionary.

    • attribute sqlalchemy.orm.InstanceState.expired_attributes = None

      The set of keys which are ‘expired’ to be loaded by the manager’s deferred scalar loader, assuming no pending changes.

      see also the unmodified collection which is intersected against this set when a refresh operation occurs.

    • attribute has_identity

      Return True if this object has an identity key.

      This should always have the same value as the expression state.persistent or state.detached.

    • attribute sqlalchemy.orm.InstanceState.identity

      Return the mapped identity of the mapped object. This is the primary key identity as persisted by the ORM which can always be passed directly to .

      Returns None if the object has no primary key identity.

      Note

      An object which is transient or does not have a mapped identity until it is flushed, even if its attributes include primary key values.

    • attribute sqlalchemy.orm.InstanceState.identity_key

      Return the identity key for the mapped object.

      This is the key used to locate the object within the mapping. It contains the identity as returned by identity within it.

    • attribute mapper

      Return the Mapper used for this mapped object.

    • attribute object

      Return the mapped object represented by this InstanceState.

    • attribute pending

      Return True if the object is pending.

      See also

    • attribute sqlalchemy.orm.InstanceState.persistent

      Return True if the object is .

      An object that is in the persistent state is guaranteed to be within the Session.identity_map of its parent .

      Changed in version 1.1: The InstanceState.persistent accessor no longer returns True for an object that was “deleted” within a flush; use the accessor to detect this state. This allows the “persistent” state to guarantee membership in the identity map.

      See also

      Quickie Intro to Object States

    • attribute session

      Return the owning Session for this instance, or None if none available.

      Note that the result here can in some cases be different from that of obj in session; an object that’s been deleted will report as not in session, however if the transaction is still in progress, this attribute will still refer to that session. Only when the transaction is completed does the object become fully detached under normal circumstances.

    • attribute transient

      Return True if the object is transient.

      See also

    • attribute sqlalchemy.orm.InstanceState.unloaded

      Return the set of keys which do not have a loaded value.

      This includes expired attributes and any other attribute that was never populated or modified.

    • attribute unloaded_expirable

      Return the set of keys which do not have a loaded value.

      This includes expired attributes and any other attribute that was never populated or modified.

    • attribute sqlalchemy.orm.InstanceState.unmodified

      Return the set of keys which have no uncommitted changes

    • method unmodified_intersection(keys)

      Return self.unmodified.intersection(keys).

    • attribute sqlalchemy.orm.InstanceState.was_deleted

      Return True if this object is or was previously in the “deleted” state and has not been reverted to persistent.

      This flag returns True once the object was deleted in flush. When the object is expunged from the session either explicitly or via transaction commit and enters the “detached” state, this flag will continue to report True.

      New in version 1.1: - added a local method form of .

      See also

      InstanceState.deleted - refers to the “deleted” state

      - standalone function

      Quickie Intro to Object States

    class sqlalchemy.orm.``InstrumentedAttribute(class_, key, parententity, impl=None, comparator=None, of_type=None, extra_criteria=())

    Class bound instrumented attribute which adds basic methods.

    See QueryableAttribute for a description of most features.

    Class signature

    class (sqlalchemy.orm.Mapped)

    sqlalchemy.orm.``MANYTOONE = symbol(‘MANYTOONE’)

    Indicates the many-to-one direction for a relationship().

    This symbol is typically used by the internals but may be exposed within certain API features.

    sqlalchemy.orm.``MANYTOMANY = symbol(‘MANYTOMANY’)

    Indicates the many-to-many direction for a .

    This symbol is typically used by the internals but may be exposed within certain API features.

    class sqlalchemy.orm.``Mapped(class_, key, parententity, impl=None, comparator=None, of_type=None, extra_criteria=())

    Represent an ORM mapped descriptor attribute for typing purposes.

    This class represents the complete descriptor interface for any class attribute that will have been by the ORM Mapper class. When used with typing stubs, it is the final type that would be used by a type checker such as mypy to provide the full behavioral contract for the attribute.

    Tip

    The class represents attributes that are handled directly by the Mapper class. It does not include other Python descriptor classes that are provided as extensions, including and the Association Proxy. While these systems still make use of ORM-specific superclasses and structures, they are not by the Mapper and instead provide their own functionality when they are accessed on a class.

    When using the , the Mapped construct is used in typing annotations to indicate to the plugin those attributes that are expected to be mapped; the plugin also applies as an annotation automatically when it scans through declarative mappings in Declarative Table style. For more indirect mapping styles such as it is typically applied explicitly to class level attributes that expect to be mapped based on a given Table configuration.

    is defined in the sqlalchemy2-stubs project as a generic class which may subscribe to any arbitrary Python type, which represents the Python type handled by the attribute:

    1. class MyMappedClass(Base):
    2. __table_ = Table(
    3. "some_table", Base.metadata,
    4. Column("id", Integer, primary_key=True),
    5. Column("data", String(50)),
    6. Column("created_at", DateTime)
    7. )
    8. id : Mapped[int]
    9. data: Mapped[str]
    10. created_at: Mapped[datetime]

    For complete background on how to use Mapped with pep-484 tools like Mypy, see the link below for background on SQLAlchemy’s Mypy plugin.

    New in version 1.4.

    See also

    - complete background on Mypy integration

    Class signature

    class sqlalchemy.orm.Mapped (, typing.Generic)

    class sqlalchemy.orm.``MapperProperty

    Represent a particular class attribute mapped by Mapper.

    The most common occurrences of are the mapped Column, which is represented in a mapping as an instance of , and a reference to another class produced by relationship(), represented in the mapping as an instance of .

    Class signature

    class sqlalchemy.orm.MapperProperty (sqlalchemy.sql.traversals.HasCacheKey, sqlalchemy.orm.base._MappedAttribute, sqlalchemy.orm.base.InspectionAttr, sqlalchemy.util.langhelpers.MemoizedSlots)

    • attribute info

      Info dictionary associated with the object, allowing user-defined data to be associated with this InspectionAttr.

      The dictionary is generated when first accessed. Alternatively, it can be specified as a constructor argument to the , relationship(), or functions.

      Changed in version 1.0.0: InspectionAttr.info moved from MapperProperty so that it can apply to a wider variety of ORM and extension constructs.

      See also

      SchemaItem.info

    • attribute cascade = frozenset({})

      The set of ‘cascade’ attribute names.

      This collection is checked before the ‘cascade_iterator’ method is called.

      The collection typically only applies to a RelationshipProperty.

    • method sqlalchemy.orm.MapperProperty.cascade_iterator(type_, state, dict_, visited_states, halt_on=None)

      Iterate through instances related to the given instance for a particular ‘cascade’, starting with this MapperProperty.

      Return an iterator3-tuples (instance, mapper, state).

      Note that the ‘cascade’ collection on this MapperProperty is checked first for the given type before cascade_iterator is called.

      This method typically only applies to RelationshipProperty.

    • attribute class_attribute

      Return the class-bound descriptor corresponding to this MapperProperty.

      This is basically a getattr() call:

      1. return getattr(self.parent.class_, self.key)

      I.e. if this were named addresses, and the class to which it is mapped is User, this sequence is possible:

      1. >>> from sqlalchemy import inspect
      2. >>> mapper = inspect(User)
      3. >>> addresses_property = mapper.attrs.addresses
      4. >>> addresses_property.class_attribute is User.addresses
      5. True
      6. >>> User.addresses.property is addresses_property
      7. True
    • method sqlalchemy.orm.MapperProperty.create_row_processor(context, query_entity, path, mapper, result, adapter, populators)

      Produce row processing functions and append to the given set of populators lists.

    • method do_init()

      Perform subclass-specific initialization post-mapper-creation steps.

      This is a template method called by the MapperProperty object’s init() method.

    • method sqlalchemy.orm.MapperProperty.init()

      Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.

    • method instrument_class(mapper)

      Hook called by the Mapper to the property to initiate instrumentation of the class attribute managed by this MapperProperty.

      The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAttribute.

      This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mapper setup process.

      The second step is typically the init_class_attribute step, called from StrategizedProperty via the post_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specifically the “impl”) which has been determined after the MapperProperty has determined what kind of persistence management it needs to do (e.g. scalar, object, collection, etc).

    • attribute sqlalchemy.orm.MapperProperty.is_property = True

      Part of the InspectionAttr interface; states this object is a mapper property.

    • method merge(session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map)

      Merge the attribute represented by this MapperProperty from source to destination object.

    • method sqlalchemy.orm.MapperProperty.post_instrument_class(mapper)

      Perform instrumentation adjustments that need to occur after init() has completed.

      The given Mapper is the Mapper invoking the operation, which may not be the same Mapper as self.parent in an inheritance scenario; however, Mapper will always at least be a sub-mapper of self.parent.

      This method is typically used by StrategizedProperty, which delegates it to LoaderStrategy.init_class_attribute() to perform final setup on the class-bound InstrumentedAttribute.

    • method set_parent(parent, init)

      Set the parent mapper that references this MapperProperty.

      This method is overridden by some subclasses to perform extra setup when the mapper is first known.

    • method sqlalchemy.orm.MapperProperty.setup(context, query_entity, path, adapter, \*kwargs*)

      Called by Query for the purposes of constructing a SQL statement.

      Each MapperProperty associated with the target mapper processes the statement referenced by the query context, adding columns and/or criterion as appropriate.

    sqlalchemy.orm.``NOT_EXTENSION = symbol(‘NOT_EXTENSION’)

    Symbol indicating an that’s not part of sqlalchemy.ext.

    Is assigned to the InspectionAttr.extension_type attribute.

    function sqlalchemy.orm.``merge_result(query, iterator, load=True)

    Merge a result into this object’s Session.

    Deprecated since version 1.4: The merge_result() method is superseded by the function. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)

    function sqlalchemy.orm.``merge_frozen_result(session, statement, frozen_result, load=True)

    Merge a back into a Session, returning a new object with persistent objects.

    See the section for an example.

    See also

    Re-Executing Statements

    FrozenResult

    sqlalchemy.orm.``ONETOMANY = symbol(‘ONETOMANY’)

    Indicates the one-to-many direction for a .

    This symbol is typically used by the internals but may be exposed within certain API features.

    class sqlalchemy.orm.``PropComparator(prop, parentmapper, adapt_to_entity=None)

    Defines SQL operators for MapperProperty objects.

    SQLAlchemy allows for operators to be redefined at both the Core and ORM level. is the base class of operator redefinition for ORM-level operations, including those of ColumnProperty, , and CompositeProperty.

    Note

    With the advent of Hybrid properties introduced in SQLAlchemy 0.7, as well as Core-level operator redefinition in SQLAlchemy 0.8, the use case for user-defined instances is extremely rare. See Hybrid Attributes as well as .

    User-defined subclasses of PropComparator may be created. The built-in Python comparison and math operator methods, such as ColumnOperators.__eq__(), ColumnOperators.__lt__(), and ColumnOperators.__add__(), can be overridden to provide new operator behavior. The custom is passed to the MapperProperty instance via the comparator_factory argument. In each case, the appropriate subclass of should be used:

    1. # definition of custom PropComparator subclasses
    2. from sqlalchemy.orm.properties import \
    3. ColumnProperty,\
    4. CompositeProperty,\
    5. RelationshipProperty
    6. class MyColumnComparator(ColumnProperty.Comparator):
    7. def __eq__(self, other):
    8. return self.__clause_element__() == other
    9. class MyRelationshipComparator(RelationshipProperty.Comparator):
    10. def any(self, expression):
    11. "define the 'any' operation"
    12. # ...
    13. class MyCompositeComparator(CompositeProperty.Comparator):
    14. def __gt__(self, other):
    15. "redefine the 'greater than' operation"
    16. return sql.and_(*[a>b for a, b in
    17. zip(self.__clause_element__().clauses,
    18. other.__composite_values__())])
    19. # application of custom PropComparator subclasses
    20. from sqlalchemy.orm import column_property, relationship, composite
    21. from sqlalchemy import Column, String
    22. class SomeMappedClass(Base):
    23. some_column = column_property(Column("some_column", String),
    24. comparator_factory=MyColumnComparator)
    25. some_relationship = relationship(SomeOtherClass,
    26. comparator_factory=MyRelationshipComparator)
    27. some_composite = composite(
    28. Column("a", String), Column("b", String),
    29. comparator_factory=MyCompositeComparator
    30. )

    Note that for column-level operator redefinition, it’s usually simpler to define the operators at the Core level, using the TypeEngine.comparator_factory attribute. See for more detail.

    See also

    Comparator

    Comparator

    Redefining and Creating New Operators

    Class signature

    class sqlalchemy.orm.PropComparator ()

    • method sqlalchemy.orm.PropComparator.__eq__(other)

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

      Implement the == operator.

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

    • method sqlalchemy.orm.PropComparator.__le__(other)

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

      Implement the <= operator.

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

    • method sqlalchemy.orm.PropComparator.__lt__(other)

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

      Implement the < operator.

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

    • method sqlalchemy.orm.PropComparator.__ne__(other)

      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.orm.PropComparator.adapt_to_entity(adapt_to_entity)

      Return a copy of this PropComparator which will use the given to produce corresponding expressions.

    • attribute sqlalchemy.orm.PropComparator.adapter

      Produce a callable that adapts column expressions to suit an aliased version of this comparator.

    • method all_()

      inherited from the ColumnOperators.all_() method of

      Produce a all_() clause against the parent object.

      This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:

      1. # postgresql '5 = ALL (somearray)'
      2. expr = 5 == mytable.c.somearray.all_()
      3. # mysql '5 = ALL (SELECT value FROM table)'
      4. expr = 5 == select(table.c.value).scalar_subquery().all_()

      See also

      - standalone version

      any_() - ANY operator

      New in version 1.1.

    • method and_(\criteria*)

      Add additional criteria to the ON clause that’s represented by this relationship attribute.

      E.g.:

      1. stmt = select(User).join(
      2. User.addresses.and_(Address.email_address != 'foo')
      3. )
      4. stmt = select(User).options(
      5. joinedload(User.addresses.and_(Address.email_address != 'foo'))
      6. )

      New in version 1.4.

      See also

      Augmenting Built-in ON Clauses

      with_loader_criteria()

    • method any(criterion=None, \*kwargs*)

      Return true if this collection contains any member that meets the given criterion.

      The usual implementation of any() is Comparator.any().

      • Parameters

        • criterion – an optional ClauseElement formulated against the member class’ table or attributes.

        • **kwargs – key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

    • method any_()

      inherited from the ColumnOperators.any_() method of

      Produce a any_() clause against the parent object.

      This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:

      1. # postgresql '5 = ANY (somearray)'
      2. expr = 5 == mytable.c.somearray.any_()
      3. # mysql '5 = ANY (SELECT value FROM table)'
      4. expr = 5 == select(table.c.value).scalar_subquery().any_()

      See also

      - standalone version

      all_() - ALL operator

      New in version 1.1.

    • method asc()

      inherited from the ColumnOperators.asc() method of

      Produce a asc() clause against the parent object.

    • method between(cleft, cright, symmetric=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, precedence=0)

      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.

      See also

      Operators.op()

    • method collate(collation)

      inherited from the ColumnOperators.collate() method of

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

      See also

    • method sqlalchemy.orm.PropComparator.concat(other)

      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, \*kwargs*)

      inherited from the ColumnOperators.contains() method of

      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 ColumnOperators.contains.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.contains.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.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 :

          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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [`ColumnOperators.endswith()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.orm.PropComparator.desc()

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.orm.PropComparator.distinct()

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.orm.PropComparator.endswith(other, \*kwargs*)

      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".

        • 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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [`ColumnOperators.contains()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method has(criterion=None, \*kwargs*)

      Return true if this element references a member which meets the given criterion.

      The usual implementation of has() is Comparator.has().

      • Parameters

        • criterion – an optional ClauseElement formulated against the member class’ table or attributes.

        • **kwargs – key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

    • method ilike(other, escape=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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.orm.PropComparator.in_(other)

      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. )

        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)

      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_not(other)

      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)

      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.orm.PropComparator.isnot(other)

      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.orm.PropComparator.isnot_distinct_from(other)

      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 like(other, escape=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. somecolumn.like("foo/%bar", escape="/")
    1. See also
    2. [`ColumnOperators.ilike()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • method sqlalchemy.orm.PropComparator.match(other, \*kwargs*)

      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 @@ to_tsquery(y)

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

      • 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.orm.PropComparator.not_ilike(other, escape=None)

      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)

      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, escape=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.orm.PropComparator.notilike(other, escape=None)

      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)

      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, escape=None)

      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.orm.PropComparator.nulls_first()

      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.orm.PropComparator.nulls_last()

      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.orm.PropComparator.nullsfirst()

      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.orm.PropComparator.nullslast()

      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.orm.PropComparator.of_type(class_)

      Redefine this object in terms of a polymorphic subclass, construct, or aliased() construct.

      Returns a new PropComparator from which further criterion can be evaluated.

      e.g.:

      1. query.join(Company.employees.of_type(Engineer)).\
      2. filter(Engineer.name=='foo')
      • Parameters

        class_ – a class or mapper indicating that criterion will be against this specific subclass.

      See also

    • method sqlalchemy.orm.PropComparator.op(opstring, precedence=0, is_comparison=False, return_type=None)

      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

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

        • precedence – precedence to apply to the operator, when parenthesizing expressions. 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.

        • is_comparison

          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 should be set so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          New in version 0.9.2: - added the flag.

        • 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.

    1. See also
    2. [Redefining and Creating New Operators]($993b6f7a0d78cd7b.md#types-operators)
    3. [Using custom operators in join conditions]($e1f42b7742e49253.md#relationship-custom-operator)
    • method operate(op, \other, **kwargs*)

      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):
      3. return op(func.lower(self), func.lower(other))
      • 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 regexp_match(pattern, flags=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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method regexp_replace(pattern, replacement, flags=None)

      inherited from the ColumnOperators.regexp_replace() method of

      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. )

      ColumnOperators.regexp_replace() 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.

    • method reverse_operate(op, other, \*kwargs*)

      inherited from the Operators.reverse_operate() method of

      Reverse operate on an argument.

      Usage is the same as operate().

    • method startswith(other, \*kwargs*)

      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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    3. [`ColumnOperators.contains()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")

    class sqlalchemy.orm.``RelationshipProperty(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, overlaps=None, post_update=False, cascade=False, viewonly=False, lazy=’select’, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, comparator_factory=None, single_parent=False, innerjoin=False, distinct_target_key=None, doc=None, active_history=False, cascade_backrefs=True, load_on_pending=False, bake_queries=True, _local_remote_pairs=None, query_class=None, info=None, omit_join=None, sync_backref=None)

    Describes an object property that holds a single item or list of items that correspond to a related database table.

    Public constructor is the relationship() function.

    See also

    Class signature

    class sqlalchemy.orm.RelationshipProperty (sqlalchemy.orm.StrategizedProperty)

    • class Comparator(prop, parentmapper, adapt_to_entity=None, of_type=None, extra_criteria=())

      Produce boolean, comparison, and other operators for attributes.

      See the documentation for PropComparator for a brief overview of ORM level operator definition.

      See also

      Comparator

      Redefining and Creating New Operators

      Class signature

      class sqlalchemy.orm.RelationshipProperty.Comparator ()

      • method sqlalchemy.orm.RelationshipProperty.Comparator.__eq__(other)

        Implement the == operator.

        In a many-to-one context, such as:

        1. MyClass.some_prop == <some object>

        this will typically produce a clause such as:

        1. mytable.related_id == <some id>

        Where <some id> is the primary key of the given object.

        The == operator provides partial functionality for non- many-to-one comparisons:

        • Comparisons against collections are not supported. Use .

        • Compared to a scalar one-to-many, will produce a clause that compares the target columns in the parent to the given target.

        • Compared to a scalar many-to-many, an alias of the association table will be rendered as well, forming a natural join that is part of the main body of the query. This will not work for queries that go beyond simple AND conjunctions of comparisons, such as those which use OR. Use explicit joins, outerjoins, or Comparator.has() for more comprehensive non-many-to-one scalar membership tests.

        • Comparisons against None given in a one-to-many or many-to-many context produce a NOT EXISTS clause.

      • method __init__(prop, parentmapper, adapt_to_entity=None, of_type=None, extra_criteria=())

        Construction of Comparator is internal to the ORM’s attribute mechanics.

      • method __le__(other)

        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)

        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)

        Implement the != operator.

        In a many-to-one context, such as:

        1. MyClass.some_prop != <some object>

        This will typically produce a clause such as:

        1. mytable.related_id != <some id>

        Where <some id> is the primary key of the given object.

        The != operator provides partial functionality for non- many-to-one comparisons:

        • Comparisons against collections are not supported. Use Comparator.contains() in conjunction with .

        • Compared to a scalar one-to-many, will produce a clause that compares the target columns in the parent to the given target.

        • Compared to a scalar many-to-many, an alias of the association table will be rendered as well, forming a natural join that is part of the main body of the query. This will not work for queries that go beyond simple AND conjunctions of comparisons, such as those which use OR. Use explicit joins, outerjoins, or Comparator.has() in conjunction with for more comprehensive non-many-to-one scalar membership tests.

        • Comparisons against None given in a one-to-many or many-to-many context produce an EXISTS clause.

      • method sqlalchemy.orm.RelationshipProperty.Comparator.adapt_to_entity(adapt_to_entity)

        Return a copy of this PropComparator which will use the given to produce corresponding expressions.

      • attribute sqlalchemy.orm.RelationshipProperty.Comparator.adapter

        inherited from the attribute of PropComparator

        Produce a callable that adapts column expressions to suit an aliased version of this comparator.

      • method all_()

        inherited from the ColumnOperators.all_() method of

        Produce a all_() clause against the parent object.

        This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:

        1. # postgresql '5 = ALL (somearray)'
        2. expr = 5 == mytable.c.somearray.all_()
        3. # mysql '5 = ALL (SELECT value FROM table)'
        4. expr = 5 == select(table.c.value).scalar_subquery().all_()

        See also

        - standalone version

        any_() - ANY operator

        New in version 1.1.

      • method and_(\other*)

        Add AND criteria.

        See PropComparator.and_() for an example.

        New in version 1.4.

      • method any(criterion=None, \*kwargs*)

        Produce an expression that tests a collection against particular criterion, using EXISTS.

        An expression like:

        1. session.query(MyClass).filter(
        2. MyClass.somereference.any(SomeRelated.x==2)
        3. )

        Will produce a query like:

        1. SELECT * FROM my_table WHERE
        2. EXISTS (SELECT 1 FROM related WHERE related.my_id=my_table.id
        3. AND related.x=2)

        Because Comparator.any() uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join.

        is particularly useful for testing for empty collections:

        1. session.query(MyClass).filter(
        2. ~MyClass.somereference.any()
        3. )

        will produce:

        1. SELECT * FROM my_table WHERE
        2. NOT (EXISTS (SELECT 1 FROM related WHERE
        3. related.my_id=my_table.id))

        Comparator.any() is only valid for collections, i.e. a that has uselist=True. For scalar references, use Comparator.has().

      • method any_()

        inherited from the ColumnOperators.any_() method of

        Produce a any_() clause against the parent object.

        This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:

        1. # postgresql '5 = ANY (somearray)'
        2. expr = 5 == mytable.c.somearray.any_()
        3. # mysql '5 = ANY (SELECT value FROM table)'
        4. expr = 5 == select(table.c.value).scalar_subquery().any_()

        See also

        - standalone version

        all_() - ALL operator

        New in version 1.1.

      • method static any_op(a, b, \*kwargs*)

        inherited from the PropComparator.any_op() method of PropComparator

      • method asc()

        inherited from the ColumnOperators.asc() method of

        Produce a asc() clause against the parent object.

      • method between(cleft, cright, symmetric=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, precedence=0)

        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.

        See also

        Operators.op()

      • method collate(collation)

        inherited from the ColumnOperators.collate() method of

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

        See also

      • method sqlalchemy.orm.RelationshipProperty.Comparator.concat(other)

        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, \*kwargs*)

        Return a simple expression that tests a collection for containment of a particular item.

        Comparator.contains() is only valid for a collection, i.e. a that implements one-to-many or many-to-many with uselist=True.

        When used in a simple one-to-many context, an expression like:

        1. MyClass.contains(other)

        Produces a clause like:

        1. mytable.id == <some id>

        Where <some id> is the value of the foreign key attribute on other which refers to the primary key of its parent object. From this it follows that Comparator.contains() is very useful when used with simple one-to-many operations.

        For many-to-many operations, the behavior of has more caveats. The association table will be rendered in the statement, producing an “implicit” join, that is, includes multiple tables in the FROM clause which are equated in the WHERE clause:

        1. query(MyClass).filter(MyClass.contains(other))

        Produces a query like:

        1. SELECT * FROM my_table, my_association_table AS
        2. my_association_table_1 WHERE
        3. my_table.id = my_association_table_1.parent_id
        4. AND my_association_table_1.child_id = <some id>

        Where <some id> would be the primary key of other. From the above, it is clear that Comparator.contains() will not work with many-to-many collections when used in queries that move beyond simple AND conjunctions, such as multiple expressions joined by OR. In such cases subqueries or explicit “outer joins” will need to be used instead. See Comparator.any() for a less-performant alternative using EXISTS, or refer to as well as Querying with Joins for more details on constructing outer joins.

      • method desc()

        inherited from the ColumnOperators.desc() method of

        Produce a desc() clause against the parent object.

      • method distinct()

        inherited from the ColumnOperators.distinct() method of

        Produce a distinct() clause against the parent object.

      • method endswith(other, \*kwargs*)

        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.

        See also

        ColumnOperators.startswith()

        ColumnOperators.like()

      • attribute entity

        The target entity referred to by this Comparator.

        This is either a or AliasedInsp object.

        This is the “target” or “remote” side of the .

      • method sqlalchemy.orm.RelationshipProperty.Comparator.has(criterion=None, \*kwargs*)

        Produce an expression that tests a scalar reference against particular criterion, using EXISTS.

        An expression like:

        1. session.query(MyClass).filter(
        2. MyClass.somereference.has(SomeRelated.x==2)
        3. )

        Will produce a query like:

        1. SELECT * FROM my_table WHERE
        2. EXISTS (SELECT 1 FROM related WHERE
        3. related.id==my_table.related_id AND related.x=2)

        Because uses a correlated subquery, its performance is not nearly as good when compared against large target tables as that of using a join.

        Comparator.has() is only valid for scalar references, i.e. a that has uselist=False. For collection references, use Comparator.any().

      • method static has_op(a, b, \*kwargs*)

        inherited from the PropComparator.has_op() method of PropComparator

      • method ilike(other, escape=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="/")

        See also

        ColumnOperators.like()

      • method in_(other)

        Produce an IN clause - this is not implemented for relationship()-based attributes at this time.

      • attribute info

        inherited from the PropComparator.info attribute of PropComparator

      • method is_(other)

        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)

        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.orm.RelationshipProperty.Comparator.is_not(other)

        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.orm.RelationshipProperty.Comparator.is_not_distinct_from(other)

        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)

        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)

        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.orm.RelationshipProperty.Comparator.like(other, escape=None)

        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="/")

        See also

      • attribute sqlalchemy.orm.RelationshipProperty.Comparator.mapper

        The target referred to by this Comparator.

        This is the “target” or “remote” side of the .

      • method sqlalchemy.orm.RelationshipProperty.Comparator.match(other, \*kwargs*)

        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 @@ to_tsquery(y)

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

        • 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.orm.RelationshipProperty.Comparator.not_ilike(other, escape=None)

        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)

        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, escape=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.orm.RelationshipProperty.Comparator.notilike(other, escape=None)

        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)

        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, escape=None)

        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.orm.RelationshipProperty.Comparator.nulls_first()

        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.orm.RelationshipProperty.Comparator.nulls_last()

        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.orm.RelationshipProperty.Comparator.nullsfirst()

        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.orm.RelationshipProperty.Comparator.nullslast()

        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.orm.RelationshipProperty.Comparator.of_type(cls)

        Redefine this object in terms of a polymorphic subclass.

        See for an example.

      • method sqlalchemy.orm.RelationshipProperty.Comparator.static of_type_op(a, class_)

        inherited from the PropComparator.of_type_op() method of

      • method sqlalchemy.orm.RelationshipProperty.Comparator.op(opstring, precedence=0, is_comparison=False, return_type=None)

        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

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

        • precedence – precedence to apply to the operator, when parenthesizing expressions. 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.

        • is_comparison

          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 should be set so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          New in version 0.9.2: - added the flag.

        • 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.

        See also

        Using custom operators in join conditions

      • method operate(op, \other, **kwargs*)

        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):
        3. return op(func.lower(self), func.lower(other))

        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 regexp_match(pattern, flags=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.

        • 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.

        New in version 1.4.

        See also

      • method sqlalchemy.orm.RelationshipProperty.Comparator.regexp_replace(pattern, replacement, flags=None)

        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.

        New in version 1.4.

        See also

        ColumnOperators.regexp_match()

      • method reverse_operate(op, other, \*kwargs*)

        inherited from the Operators.reverse_operate() method of

        Reverse operate on an argument.

        Usage is the same as operate().

      • method (other, \*kwargs*)

        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.

        See also

        ColumnOperators.endswith()

        ColumnOperators.like()

      • attribute timetuple = None

        inherited from the ColumnOperators.timetuple attribute of

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

    • method sqlalchemy.orm.RelationshipProperty.__init__(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, overlaps=None, post_update=False, cascade=False, viewonly=False, lazy=’select’, collection_class=None, passive_deletes=False, passive_updates=True, remote_side=None, enable_typechecks=True, join_depth=None, comparator_factory=None, single_parent=False, innerjoin=False, distinct_target_key=None, doc=None, active_history=False, cascade_backrefs=True, load_on_pending=False, bake_queries=True, _local_remote_pairs=None, query_class=None, info=None, omit_join=None, sync_backref=None)

      Construct a new object.

      This constructor is mirrored as a public API function; see sqlalchemy.orm.relationship() for a full usage and argument description.

    • method cascade_iterator(type_, state, dict_, visited_states, halt_on=None)

      Iterate through instances related to the given instance for a particular ‘cascade’, starting with this MapperProperty.

      Return an iterator3-tuples (instance, mapper, state).

      Note that the ‘cascade’ collection on this MapperProperty is checked first for the given type before cascade_iterator is called.

      This method typically only applies to RelationshipProperty.

    • attribute sqlalchemy.orm.RelationshipProperty.class_attribute

      inherited from the attribute of MapperProperty

      Return the class-bound descriptor corresponding to this .

      This is basically a getattr() call:

      1. return getattr(self.parent.class_, self.key)

      I.e. if this MapperProperty were named addresses, and the class to which it is mapped is User, this sequence is possible:

      1. >>> from sqlalchemy import inspect
      2. >>> mapper = inspect(User)
      3. >>> addresses_property = mapper.attrs.addresses
      4. >>> addresses_property.class_attribute is User.addresses
      5. True
      6. >>> User.addresses.property is addresses_property
      7. True
    • method create_row_processor(context, query_entity, path, mapper, result, adapter, populators)

      inherited from the StrategizedProperty.create_row_processor() method of StrategizedProperty

      Produce row processing functions and append to the given set of populators lists.

    • method sqlalchemy.orm.RelationshipProperty.do_init()

      Perform subclass-specific initialization post-mapper-creation steps.

      This is a template method called by the MapperProperty object’s init() method.

    • attribute entity

      Return the target mapped entity, which is an inspect() of the class or aliased class that is referred towards.

    • attribute sqlalchemy.orm.RelationshipProperty.extension_type = symbol(‘NOT_EXTENSION’)

      inherited from the InspectionAttr.extension_type attribute of InspectionAttr

      The extension type, if any. Defaults to NOT_EXTENSION

      See also

      HYBRID_PROPERTY

    • method sqlalchemy.orm.RelationshipProperty.init()

      inherited from the method of MapperProperty

      Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.

    • method instrument_class(mapper)

      Hook called by the Mapper to the property to initiate instrumentation of the class attribute managed by this MapperProperty.

      The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAttribute.

      This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mapper setup process.

      The second step is typically the init_class_attribute step, called from StrategizedProperty via the post_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specifically the “impl”) which has been determined after the MapperProperty has determined what kind of persistence management it needs to do (e.g. scalar, object, collection, etc).

    • attribute sqlalchemy.orm.RelationshipProperty.mapper

      Return the targeted for this RelationshipProperty.

      This is a lazy-initializing static attribute.

    • method merge(session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map)

      Merge the attribute represented by this MapperProperty from source to destination object.

    • method sqlalchemy.orm.RelationshipProperty.post_instrument_class(mapper)

      inherited from the StrategizedProperty.post_instrument_class() method of StrategizedProperty

      Perform instrumentation adjustments that need to occur after init() has completed.

      The given Mapper is the Mapper invoking the operation, which may not be the same Mapper as self.parent in an inheritance scenario; however, Mapper will always at least be a sub-mapper of self.parent.

      This method is typically used by StrategizedProperty, which delegates it to LoaderStrategy.init_class_attribute() to perform final setup on the class-bound InstrumentedAttribute.

    • method set_parent(parent, init)

      inherited from the MapperProperty.set_parent() method of

      Set the parent mapper that references this MapperProperty.

      This method is overridden by some subclasses to perform extra setup when the mapper is first known.

    • method sqlalchemy.orm.RelationshipProperty.setup(context, query_entity, path, adapter, \*kwargs*)

      inherited from the StrategizedProperty.setup() method of StrategizedProperty

      Called by Query for the purposes of constructing a SQL statement.

      Each MapperProperty associated with the target mapper processes the statement referenced by the query context, adding columns and/or criterion as appropriate.

    class sqlalchemy.orm.``SynonymProperty(name, map_column=None, descriptor=None, comparator_factory=None, doc=None, info=None)

    Class signature

    class (sqlalchemy.orm.descriptor_props.DescriptorProperty)

    • method sqlalchemy.orm.SynonymProperty.__init__(name, map_column=None, descriptor=None, comparator_factory=None, doc=None, info=None)

      Construct a new object.

      This constructor is mirrored as a public API function; see sqlalchemy.orm.synonym() for a full usage and argument description.

    • method cascade_iterator(type_, state, dict_, visited_states, halt_on=None)

      inherited from the MapperProperty.cascade_iterator() method of

      Iterate through instances related to the given instance for a particular ‘cascade’, starting with this MapperProperty.

      Return an iterator3-tuples (instance, mapper, state).

      Note that the ‘cascade’ collection on this MapperProperty is checked first for the given type before cascade_iterator is called.

      This method typically only applies to RelationshipProperty.

    • attribute sqlalchemy.orm.SynonymProperty.class_attribute

      inherited from the attribute of MapperProperty

      Return the class-bound descriptor corresponding to this .

      This is basically a getattr() call:

      1. return getattr(self.parent.class_, self.key)

      I.e. if this MapperProperty were named addresses, and the class to which it is mapped is User, this sequence is possible:

      1. >>> from sqlalchemy import inspect
      2. >>> mapper = inspect(User)
      3. >>> addresses_property = mapper.attrs.addresses
      4. >>> addresses_property.class_attribute is User.addresses
      5. True
      6. >>> User.addresses.property is addresses_property
      7. True
    • method create_row_processor(context, query_entity, path, mapper, result, adapter, populators)

      inherited from the MapperProperty.create_row_processor() method of

      Produce row processing functions and append to the given set of populators lists.

    • method sqlalchemy.orm.SynonymProperty.do_init()

      inherited from the method of MapperProperty

      Perform subclass-specific initialization post-mapper-creation steps.

      This is a template method called by the MapperProperty object’s init() method.

    • attribute extension_type = symbol(‘NOT_EXTENSION’)

      inherited from the InspectionAttr.extension_type attribute of InspectionAttr

      The extension type, if any. Defaults to NOT_EXTENSION

      See also

      HYBRID_METHOD

      ASSOCIATION_PROXY

    • method init()

      inherited from the MapperProperty.init() method of

      Called after all mappers are created to assemble relationships between mappers and perform other post-mapper-creation initialization steps.

    • method sqlalchemy.orm.SynonymProperty.instrument_class(mapper)

      inherited from the DescriptorProperty.instrument_class() method of DescriptorProperty

      Hook called by the Mapper to the property to initiate instrumentation of the class attribute managed by this MapperProperty.

      The MapperProperty here will typically call out to the attributes module to set up an InstrumentedAttribute.

      This step is the first of two steps to set up an InstrumentedAttribute, and is called early in the mapper setup process.

      The second step is typically the init_class_attribute step, called from StrategizedProperty via the post_instrument_class() hook. This step assigns additional state to the InstrumentedAttribute (specifically the “impl”) which has been determined after the MapperProperty has determined what kind of persistence management it needs to do (e.g. scalar, object, collection, etc).

    • method merge(session, source_state, source_dict, dest_state, dest_dict, load, _recursive, _resolve_conflict_map)

      inherited from the MapperProperty.merge() method of

      Merge the attribute represented by this MapperProperty from source to destination object.

    • method sqlalchemy.orm.SynonymProperty.post_instrument_class(mapper)

      inherited from the method of MapperProperty

      Perform instrumentation adjustments that need to occur after init() has completed.

      The given Mapper is the Mapper invoking the operation, which may not be the same Mapper as self.parent in an inheritance scenario; however, Mapper will always at least be a sub-mapper of self.parent.

      This method is typically used by StrategizedProperty, which delegates it to LoaderStrategy.init_class_attribute() to perform final setup on the class-bound InstrumentedAttribute.

    • method set_parent(parent, init)

      Set the parent mapper that references this MapperProperty.

      This method is overridden by some subclasses to perform extra setup when the mapper is first known.

    • method sqlalchemy.orm.SynonymProperty.setup(context, query_entity, path, adapter, \*kwargs*)

      inherited from the method of MapperProperty

      Called by Query for the purposes of constructing a SQL statement.

      Each MapperProperty associated with the target mapper processes the statement referenced by the query context, adding columns and/or criterion as appropriate.

    • attribute uses_objects

    class sqlalchemy.orm.``QueryContext(compile_state, statement, params, session, load_options, execution_options=None, bind_arguments=None)

    class sqlalchemy.orm.``QueryableAttribute(class_, key, parententity, impl=None, comparator=None, of_type=None, extra_criteria=())

    Base class for objects that intercept attribute events on behalf of a MapperProperty object. The actual is accessible via the QueryableAttribute.property attribute.

    See also

    MapperProperty

    Mapper.attrs

    Class signature

    class (sqlalchemy.orm.base._MappedAttribute, sqlalchemy.orm.base.InspectionAttr, sqlalchemy.orm.PropComparator, sqlalchemy.sql.traversals.HasCopyInternals, sqlalchemy.sql.roles.JoinTargetRole, sqlalchemy.sql.roles.OnClauseRole, sqlalchemy.sql.expression.Immutable, sqlalchemy.sql.traversals.MemoizedHasCacheKey)

    • method __eq__(other)

      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)

      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)

      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)

      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 adapt_to_entity(adapt_to_entity)

      Return a copy of this PropComparator which will use the given AliasedInsp to produce corresponding expressions.

    • attribute adapter

      inherited from the PropComparator.adapter attribute of

      Produce a callable that adapts column expressions to suit an aliased version of this comparator.

    • method sqlalchemy.orm.QueryableAttribute.all_()

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:

      1. # postgresql '5 = ALL (somearray)'
      2. expr = 5 == mytable.c.somearray.all_()
      3. # mysql '5 = ALL (SELECT value FROM table)'
      4. expr = 5 == select(table.c.value).scalar_subquery().all_()

      See also

      all_() - standalone version

      - ANY operator

      New in version 1.1.

    • method sqlalchemy.orm.QueryableAttribute.and_(\other*)

      Add additional criteria to the ON clause that’s represented by this relationship attribute.

      E.g.:

      New in version 1.4.

      See also

      Adding Criteria to loader options

    • method sqlalchemy.orm.QueryableAttribute.any(criterion=None, \*kwargs*)

      inherited from the method of PropComparator

      Return true if this collection contains any member that meets the given criterion.

      The usual implementation of any() is .

      • Parameters

        • criterion – an optional ClauseElement formulated against the member class’ table or attributes.

        • **kwargs – key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

    • method sqlalchemy.orm.QueryableAttribute.any_()

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

      This operator is only appropriate against a scalar subquery object, or for some backends an column expression that is against the ARRAY type, e.g.:

      1. # postgresql '5 = ANY (somearray)'
      2. expr = 5 == mytable.c.somearray.any_()
      3. # mysql '5 = ANY (SELECT value FROM table)'
      4. expr = 5 == select(table.c.value).scalar_subquery().any_()

      See also

      any_() - standalone version

      - ALL operator

      New in version 1.1.

    • method sqlalchemy.orm.QueryableAttribute.asc()

      inherited from the method of ColumnOperators

      Produce a clause against the parent object.

    • method sqlalchemy.orm.QueryableAttribute.between(cleft, cright, symmetric=False)

      inherited from the method of ColumnOperators

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

    • method sqlalchemy.orm.QueryableAttribute.bool_op(opstring, precedence=0)

      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.

      See also

    • method sqlalchemy.orm.QueryableAttribute.collate(collation)

      inherited from the method of ColumnOperators

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

      See also

      collate()

    • method concat(other)

      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.orm.QueryableAttribute.contains(other, \*kwargs*)

      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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [`ColumnOperators.endswith()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method desc()

      inherited from the ColumnOperators.desc() method of

      Produce a desc() clause against the parent object.

    • method distinct()

      inherited from the ColumnOperators.distinct() method of

      Produce a distinct() clause against the parent object.

    • method endswith(other, \*kwargs*)

      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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.startswith "sqlalchemy.sql.expression.ColumnOperators.startswith")
    3. [`ColumnOperators.contains()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • attribute sqlalchemy.orm.QueryableAttribute.expression

      The SQL expression object represented by this .

      This will typically be an instance of a ColumnElement subclass representing a column expression.

    • attribute extension_type = symbol(‘NOT_EXTENSION’)

      inherited from the InspectionAttr.extension_type attribute of InspectionAttr

      The extension type, if any. Defaults to NOT_EXTENSION

      See also

      HYBRID_METHOD

      ASSOCIATION_PROXY

    • method has(criterion=None, \*kwargs*)

      inherited from the PropComparator.has() method of

      Return true if this element references a member which meets the given criterion.

      The usual implementation of has() is Comparator.has().

      • Parameters

        • criterion – an optional ClauseElement formulated against the member class’ table or attributes.

        • **kwargs – key/value pairs corresponding to member class attribute names which will be compared via equality to the corresponding values.

    • method ilike(other, escape=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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")
    • method sqlalchemy.orm.QueryableAttribute.in_(other)

      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

      Return the ‘info’ dictionary for the underlying SQL element.

      The behavior here is as follows:

      • If the attribute is a column-mapped property, i.e. ColumnProperty, which is mapped directly to a schema-level object, this attribute will return the SchemaItem.info dictionary associated with the core-level object.

      • If the attribute is a ColumnProperty but is mapped to any other kind of SQL expression other than a , the attribute will refer to the MapperProperty.info dictionary associated directly with the , assuming the SQL expression itself does not have its own .info attribute (which should be the case, unless a user-defined SQL construct has defined one).

      • If the attribute refers to any other kind of MapperProperty, including , the attribute will refer to the MapperProperty.info dictionary associated with that .

      • To access the MapperProperty.info dictionary of the unconditionally, including for a ColumnProperty that’s associated directly with a , the attribute can be referred to using QueryableAttribute.property attribute, as MyClass.someattribute.property.info.

      See also

      MapperProperty.info

    • method is_(other)

      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)

      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.orm.QueryableAttribute.is_not(other)

      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.orm.QueryableAttribute.is_not_distinct_from(other)

      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)

      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)

      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.orm.QueryableAttribute.like(other, escape=None)

      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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.ilike "sqlalchemy.sql.expression.ColumnOperators.ilike")
    • method match(other, \*kwargs*)

      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 @@ to_tsquery(y)

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

      • 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.

    • class memoized_attribute(fget, doc=None)

      A read-only @property that is only evaluated once.

    • method classmethod memoized_instancemethod(fn)

      inherited from the HasMemoized.memoized_instancemethod() method of HasMemoized

      Decorate a method memoize its return value.

    • method sqlalchemy.orm.QueryableAttribute.not_ilike(other, escape=None)

      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)

      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, escape=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.orm.QueryableAttribute.notilike(other, escape=None)

      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)

      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, escape=None)

      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.orm.QueryableAttribute.nulls_first()

      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.orm.QueryableAttribute.nulls_last()

      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.orm.QueryableAttribute.nullsfirst()

      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.orm.QueryableAttribute.nullslast()

      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.orm.QueryableAttribute.of_type(entity)

      Redefine this object in terms of a polymorphic subclass, construct, or aliased() construct.

      Returns a new PropComparator from which further criterion can be evaluated.

      e.g.:

      1. query.join(Company.employees.of_type(Engineer)).\
      2. filter(Engineer.name=='foo')
      • Parameters

        class_ – a class or mapper indicating that criterion will be against this specific subclass.

      See also

    • method sqlalchemy.orm.QueryableAttribute.op(opstring, precedence=0, is_comparison=False, return_type=None)

      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

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

        • precedence – precedence to apply to the operator, when parenthesizing expressions. 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.

        • is_comparison

          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 should be set so that ORM relationships can establish that the operator is a comparison operator when used in a custom join condition.

          New in version 0.9.2: - added the flag.

        • 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.

    1. See also
    2. [Redefining and Creating New Operators]($993b6f7a0d78cd7b.md#types-operators)
    3. [Using custom operators in join conditions]($e1f42b7742e49253.md#relationship-custom-operator)
    • method operate(op, \other, **kwargs*)

      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):
      3. return op(func.lower(self), func.lower(other))
      • 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

      Return an inspection instance representing the parent.

      This will be either an instance of Mapper or , depending upon the nature of the parent entity which this attribute is associated with.

    • attribute sqlalchemy.orm.QueryableAttribute.property

      Return the associated with this QueryableAttribute.

      Return values here will commonly be instances of or RelationshipProperty.

    • method regexp_match(pattern, flags=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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.regexp_replace "sqlalchemy.sql.expression.ColumnOperators.regexp_replace")
    • method regexp_replace(pattern, replacement, flags=None)

      inherited from the ColumnOperators.regexp_replace() method of

      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. )

      ColumnOperators.regexp_replace() 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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.regexp_match "sqlalchemy.sql.expression.ColumnOperators.regexp_match")
    • method reverse_operate(op, other, \*kwargs*)

      Reverse operate on an argument.

      Usage is the same as operate().

    • method startswith(other, \*kwargs*)

      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()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.endswith "sqlalchemy.sql.expression.ColumnOperators.endswith")
    3. [`ColumnOperators.contains()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.contains "sqlalchemy.sql.expression.ColumnOperators.contains")
    4. [`ColumnOperators.like()`]($f62ce11674ae62ed.md#sqlalchemy.sql.expression.ColumnOperators.like "sqlalchemy.sql.expression.ColumnOperators.like")

    class sqlalchemy.orm.``UOWTransaction(session)

    • method sqlalchemy.orm.UOWTransaction.filter_states_for_dep(dep, states)

      Filter the given list of InstanceStates to those relevant to the given DependencyProcessor.

    • method finalize_flush_changes()

      Mark processed objects as clean / deleted after a successful flush().

      This method is called within the flush() method after the execute() method has succeeded and the transaction has been committed.

    • method sqlalchemy.orm.UOWTransaction.get_attribute_history(state, key, passive=symbol(‘PASSIVE_NO_INITIALIZE’))

      Facade to attributes.get_state_history(), including caching of results.

    • method is_deleted(state)

      Return True if the given state is marked as deleted within this uowtransaction.

    • Return if the given state is expired and was deleted previously.