Release: 1.2.12 current release | Release Date: September 19, 2018

# ORM Internals¶

Key ORM constructs, not otherwise covered in other sections, are listed here.

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

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

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

from sqlalchemy import inspect

insp = inspect(some_mapped_object)
attr_state = insp.attrs.some_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.

AttributeState.load_history() - retrieve history using loader callables if the value is not locally present.

attributes.get_history() - underlying function

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.

New in version 0.9.0.

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.

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.util.CascadeOptions

Bases: __builtin__.frozenset

Keeps track of the options sent to relationship().cascade

class sqlalchemy.orm.instrumentation.ClassManager(class_)

Bases: __builtin__.dict

tracks state information at the class level.

__le__
inherited from the __le__ attribute of dict

x.__le__(y) <==> x<=y

__lt__
inherited from the __lt__ attribute of dict

x.__lt__(y) <==> x<y

__ne__
inherited from the __ne__ attribute of dict

x.__ne__(y) <==> x!=y

clear() → None. Remove all items from D.
inherited from the clear() method of dict
copy() → a shallow copy of D
inherited from the copy() method of dict
dispose()

Dissasociate this manager from its class.

fromkeys(S[, v]) → New dict with keys from S and values equal to v.
inherited from the fromkeys() method of dict

v defaults to None.

get(k[, d]) → D[k] if k in D, else d. d defaults to None.
inherited from the get() method of dict
has_key(k) → True if D has a key k, else False
inherited from the has_key() method of dict
has_parent(state, key, optimistic=False)

TODO

items() → list of D's (key, value) pairs, as 2-tuples
inherited from the items() method of dict
iteritems() → an iterator over the (key, value) items of D
inherited from the iteritems() method of dict
iterkeys() → an iterator over the keys of D
inherited from the iterkeys() method of dict
itervalues() → an iterator over the values of D
inherited from the itervalues() method of dict
keys() → list of D's keys
inherited from the keys() method of dict
manage()

Mark this instance as the manager for its class.

original_init

x.__init__(…) initializes x; see help(type(x)) for signature

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

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

popitem() → (k, v), remove and return some (key, value) pair as a
inherited from the popitem() method of dict

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

setdefault(k[, d]) → D.get(k,d), also set D[k]=d if k not in D
inherited from the setdefault() method of dict
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.

unregister()

remove all instrumentation established by this ClassManager.

update([E, ]**F) → None. Update D from dict/iterable E and F.
inherited from the update() method of dict

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

values() → list of D's values
inherited from the values() method of dict
viewitems() → a set-like object providing a view on D's items
inherited from the viewitems() method of dict
viewkeys() → a set-like object providing a view on D's keys
inherited from the viewkeys() method of dict
viewvalues() → an object providing a view on D's values
inherited from the viewvalues() method of dict
class sqlalchemy.orm.properties.ColumnProperty(*columns, **kwargs)

Bases: sqlalchemy.orm.interfaces.StrategizedProperty

Describes an object attribute that corresponds to a table column.

Public constructor is the orm.column_property() function.

class Comparator(prop, parentmapper, adapt_to_entity=None)

Bases: sqlalchemy.util.langhelpers.MemoizedSlots, sqlalchemy.orm.interfaces.PropComparator

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

See the documentation for PropComparator for a brief overview.

PropComparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

__eq__(other)

Implement the == operator.

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

__le__(other)

Implement the <= operator.

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

__lt__(other)

Implement the < operator.

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

__ne__(other)

Implement the != operator.

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

adapt_to_entity(adapt_to_entity)

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

adapter
inherited from the adapter attribute of PropComparator

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

all_()

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

# postgresql '5 = ALL (somearray)'
expr = 5 == mytable.c.somearray.all_()

# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().all_()

all_() - standalone version

any_() - ANY operator

New in version 1.1.

any(criterion=None, **kwargs)

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

The usual implementation of any() is RelationshipProperty.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.
any_()

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

# postgresql '5 = ANY (somearray)'
expr = 5 == mytable.c.somearray.any_()

# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().any_()

any_() - standalone version

all_() - ALL operator

New in version 1.1.

asc()

Produce a asc() clause against the parent object.

between(cleft, cright, symmetric=False)

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

bool_op(opstring, precedence=0)
inherited from the bool_op() method of Operators

Return a custom boolean operator.

This method is shorthand for calling Operators.op() and passing the Operators.op.is_comparison flag with True.

New in version 1.2.0b3.

collate(collation)

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

concat(other)

Implement the ‘concat’ operator.

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

contains(other, **kwargs)

Implement the ‘contains’ operator.

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

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

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.contains("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.contains.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.contains.escape parameter. 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: somecolumn.contains("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.contains.autoescape: 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.
desc()

Produce a desc() clause against the parent object.

distinct()

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)

Implement the ‘endswith’ operator.

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

column LIKE '%' || <other>

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.endswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.endswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.endswith.escape parameter. 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: somecolumn.endswith("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param ESCAPE '^' The parameter may also be combined with ColumnOperators.endswith.autoescape: 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.
has(criterion=None, **kwargs)

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

The usual implementation of has() is RelationshipProperty.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.
ilike(other, escape=None)

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

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

lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

a ILIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.ilike("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.ilike("foo/%bar", escape="/")
in_(other)

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

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:

WHERE COL IN (?, ?, ?)
• An empty list, e.g.:

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

In this calling form, the expression renders a “false” expression, e.g.:

WHERE 1 != 1

This “false” expression has historically had different behaviors in older SQLAlchemy versions, see create_engine.empty_in_strategy for behavioral options.

Changed in version 1.2: simplified the behavior of “empty in” expressions

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

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

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

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:

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

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

WHERE COL IN (?, ?, ?)

New in version 1.2: added “expanding” bound parameters

The “expanding” feature in version 1.2 of SQLAlchemy does not support passing an empty list as a parameter value; however, version 1.3 does support this.

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

stmt.where(
column.in_(
select([othertable.c.y]).
where(table.c.x == othertable.c.x)
)
)

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

WHERE COL IN (SELECT othertable.y
FROM othertable WHERE othertable.x = table.x)
Parameters: other¶ – a list of literals, a select() construct, or a bindparam() construct that includes the bindparam.expanding flag set to True.
is_(other)

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.

New in version 0.7.9.

is_distinct_from(other)

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.

isnot(other)

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.

New in version 0.7.9.

isnot_distinct_from(other)

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

New in version 1.1.

like(other, escape=None)

Implement the like operator.

In a column context, produces the expression:

a LIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.like("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)

Implements a database-specific ‘match’ operator.

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

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)

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 create_engine.empty_in_strategy may be used to alter this behavior.

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

notlike(other, escape=None)

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()

Produce a nullsfirst() clause against the parent object.

nullslast()

Produce a nullslast() clause against the parent object.

of_type(class_)

Redefine this object in terms of a polymorphic subclass.

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

e.g.:

query.join(Company.employees.of_type(Engineer)).\
filter(Engineer.name=='foo')
Parameters: class_¶ – a class or mapper indicating that criterion will be against this specific subclass.
op(opstring, precedence=0, is_comparison=False, return_type=None)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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. New in version 0.8: - added the ‘precedence’ argument. 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 Operators.op.is_comparison 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 Operators.op.is_comparison will resolve to Boolean, and those that do not will be of the same type as the left-hand operand. New in version 1.2.0b3: - added the Operators.op.return_type argument.
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:

class MyComparator(ColumnOperators):
def operate(self, op, other):
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().
reverse_operate(op, other, **kwargs)

Reverse operate on an argument.

Usage is the same as operate().

startswith(other, **kwargs)

Implement the startswith operator.

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

column LIKE <other> || '%'

E.g.:

stmt = select([sometable]).\
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 occurences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

Parameters: other¶ – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the 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: somecolumn.startswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.startswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.startswith.escape parameter. 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: somecolumn.startswith("foo/%bar", escape="^") Will render as: somecolumn LIKE :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.startswith.autoescape: 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.
__init__(*columns, **kwargs)

Construct a new ColumnProperty object.

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

cascade_iterator(type_, state, visited_instances=None, 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.

class_attribute

Return the class-bound descriptor corresponding to this MapperProperty.

This is basically a getattr() call:

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:

>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
True
True
create_row_processor(context, path, mapper, result, adapter, populators)
inherited from the create_row_processor() method of StrategizedProperty

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

do_init()

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

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

expression

Return the primary column or expression for this ColumnProperty.

extension_type = symbol('NOT_EXTENSION')
init()

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

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

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.

post_instrument_class(mapper)
inherited from the 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.

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.

setup(context, entity, path, adapter, **kwargs)
inherited from the 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.properties.ComparableProperty(comparator_factory, descriptor=None, doc=None, info=None)

Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty

Instruments a Python property for use in query expressions.

__init__(comparator_factory, descriptor=None, doc=None, info=None)

Construct a new ComparableProperty object.

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

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

Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty

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

CompositeProperty is constructed using the composite() function.

class Comparator(prop, parentmapper, adapt_to_entity=None)

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

See the example in Redefining Comparison Operations for Composites for an overview of usage , as well as the documentation for PropComparator.

PropComparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

class CompositeBundle(property, expr)
create_row_processor(query, procs, labels)

Produce the “row processing” function for this Bundle.

May be overridden by subclasses.

Column Bundles - includes an example of subclassing.

__init__(class_, *attrs, **kwargs)

Construct a new CompositeProperty object.

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

do_init()

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

get_history(state, dict_, passive=symbol('PASSIVE_OFF'))

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

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.attributes.Event(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.append(), AttributeEvents.set(), and AttributeEvents.remove().

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.

Variables: impl – The AttributeImpl which is the current event initiator. op – The symbol OP_APPEND, OP_REMOVE, OP_REPLACE, or OP_BULK_REPLACE, indicating the source operation.
class sqlalchemy.orm.identity.IdentityMap
check_modified()

return True if any InstanceStates present have been marked as ‘modified’.

class sqlalchemy.orm.base.InspectionAttr

A base class applied to all ORM objects that can be returned by the inspect() 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.

extension_type = symbol('NOT_EXTENSION')

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

New in version 0.8.0.

is_aliased_class = False

True if this object is an instance of AliasedClass.

is_attribute = False

True if this object is a Python descriptor.

This can refer to one of many types. Usually a QueryableAttribute which handles attributes events on behalf of a MapperProperty. But can also be an extension type such as AssociationProxy or hybrid_property. The InspectionAttr.extension_type will refer to a constant identifying the specific subtype.

is_clause_element = False

True if this object is an instance of ClauseElement.

is_instance = False

True if this object is an instance of InstanceState.

is_mapper = False

True if this object is an instance of Mapper.

is_property = False

True if this object is an instance of MapperProperty.

is_selectable = False

Return True if this object is an instance of Selectable.

class sqlalchemy.orm.base.InspectionAttrInfo

Adds the .info attribute to InspectionAttr.

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

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 column_property(), relationship(), or composite() functions.

New in version 0.8: Added support for .info to all MapperProperty subclasses.

Changed in version 1.0.0: MapperProperty.info 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.

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

tracks state information at the instance level.

The InstanceState 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.

InstanceState 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 InstanceState object is to use the inspect() system:

>>> from sqlalchemy import inspect
>>> insp = inspect(some_mapped_object)
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.

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.

deleted

Return true if the object is deleted.

An object that is in the deleted state is guaranteed to not be within the Session.identity_map of its parent Session; 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 detached, 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 Session, use the InstanceState.was_deleted accessor.

detached

Return true if the object is detached.

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.

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.

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.

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 Query.get().

Returns None if the object has no primary key identity.

Note

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

identity_key

Return the identity key for the mapped object.

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

mapper

Return the Mapper used for this mapepd object.

object

Return the mapped object represented by this InstanceState.

pending

Return true if the object is pending.

persistent

Return true if the object is persistent.

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

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

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.

transient

Return true if the object is transient.

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.

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.

unmodified

Return the set of keys which have no uncommitted changes

unmodified_intersection(keys)

Return self.unmodified.intersection(keys).

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 orm.util.was_deleted().

InstanceState.deleted - refers to the “deleted” state

orm.util.was_deleted() - standalone function

Quickie Intro to Object States

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

Class bound instrumented attribute which adds basic descriptor methods.

See QueryableAttribute for a description of most features.

__delete__(instance)
__get__(instance, owner)
__set__(instance, value)
sqlalchemy.orm.interfaces.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.interfaces.MANYTOMANY = symbol('MANYTOMANY')

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

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

class sqlalchemy.orm.interfaces.MapperProperty

Bases: sqlalchemy.orm.base._MappedAttribute, sqlalchemy.orm.base.InspectionAttr, sqlalchemy.util.langhelpers.MemoizedSlots

Represent a particular class attribute mapped by Mapper.

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

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 column_property(), relationship(), or composite() functions.

New in version 0.8: Added support for .info to all MapperProperty subclasses.

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.

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.

cascade_iterator(type_, state, visited_instances=None, 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.

class_attribute

Return the class-bound descriptor corresponding to this MapperProperty.

This is basically a getattr() call:

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:

>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
True
True
create_row_processor(context, path, mapper, result, adapter, populators)

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

do_init()

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

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

init()

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

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

is_property = True

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

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.

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.

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.

setup(context, 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.interfaces.NOT_EXTENSION = symbol('NOT_EXTENSION')

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

Is assigned to the InspectionAttr.extension_type attibute.

sqlalchemy.orm.interfaces.ONETOMANY = symbol('ONETOMANY')

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

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

class sqlalchemy.orm.interfaces.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. PropComparator is the base class of operator redefinition for ORM-level operations, including those of ColumnProperty, RelationshipProperty, 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 PropComparator instances is extremely rare. See Hybrid Attributes as well as Redefining and Creating New Operators.

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

# definition of custom PropComparator subclasses

from sqlalchemy.orm.properties import \
ColumnProperty,\
CompositeProperty,\
RelationshipProperty

class MyColumnComparator(ColumnProperty.Comparator):
def __eq__(self, other):
return self.__clause_element__() == other

class MyRelationshipComparator(RelationshipProperty.Comparator):
def any(self, expression):
"define the 'any' operation"
# ...

class MyCompositeComparator(CompositeProperty.Comparator):
def __gt__(self, other):
"redefine the 'greater than' operation"

return sql.and_(*[a>b for a, b in
zip(self.__clause_element__().clauses,
other.__composite_values__())])

# application of custom PropComparator subclasses

from sqlalchemy.orm import column_property, relationship, composite
from sqlalchemy import Column, String

class SomeMappedClass(Base):
some_column = column_property(Column("some_column", String),
comparator_factory=MyColumnComparator)

some_relationship = relationship(SomeOtherClass,
comparator_factory=MyRelationshipComparator)

some_composite = composite(
Column("a", String), Column("b", String),
comparator_factory=MyCompositeComparator
)

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 Redefining and Creating New Operators for more detail.

ColumnProperty.Comparator

RelationshipProperty.Comparator

CompositeProperty.Comparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

__eq__(other)

Implement the == operator.

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

__le__(other)

Implement the <= operator.

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

__lt__(other)

Implement the < operator.

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

__ne__(other)

Implement the != operator.

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

adapt_to_entity(adapt_to_entity)

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

adapter

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

all_()

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

# postgresql '5 = ALL (somearray)'
expr = 5 == mytable.c.somearray.all_()

# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().all_()

all_() - standalone version

any_() - ANY operator

New in version 1.1.

any(criterion=None, **kwargs)

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

The usual implementation of any() is RelationshipProperty.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.
any_()

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

# postgresql '5 = ANY (somearray)'
expr = 5 == mytable.c.somearray.any_()

# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().any_()

any_() - standalone version

all_() - ALL operator

New in version 1.1.

asc()

Produce a asc() clause against the parent object.

between(cleft, cright, symmetric=False)

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

bool_op(opstring, precedence=0)
inherited from the bool_op() method of Operators

Return a custom boolean operator.

This method is shorthand for calling Operators.op() and passing the Operators.op.is_comparison flag with True.

New in version 1.2.0b3.

collate(collation)

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

concat(other)

Implement the ‘concat’ operator.

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

contains(other, **kwargs)

Implement the ‘contains’ operator.

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

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

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.contains("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.contains.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.contains.escape parameter. 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: somecolumn.contains("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.contains.autoescape: 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.
desc()

Produce a desc() clause against the parent object.

distinct()

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)

Implement the ‘endswith’ operator.

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

column LIKE '%' || <other>

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.endswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.endswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.endswith.escape parameter. 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: somecolumn.endswith("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param ESCAPE '^' The parameter may also be combined with ColumnOperators.endswith.autoescape: 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.
has(criterion=None, **kwargs)

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

The usual implementation of has() is RelationshipProperty.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.
ilike(other, escape=None)

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

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

lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

a ILIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.ilike("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.ilike("foo/%bar", escape="/")
in_(other)

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

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:

WHERE COL IN (?, ?, ?)
• An empty list, e.g.:

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

In this calling form, the expression renders a “false” expression, e.g.:

WHERE 1 != 1

This “false” expression has historically had different behaviors in older SQLAlchemy versions, see create_engine.empty_in_strategy for behavioral options.

Changed in version 1.2: simplified the behavior of “empty in” expressions

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

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

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

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:

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

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

WHERE COL IN (?, ?, ?)

New in version 1.2: added “expanding” bound parameters

The “expanding” feature in version 1.2 of SQLAlchemy does not support passing an empty list as a parameter value; however, version 1.3 does support this.

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

stmt.where(
column.in_(
select([othertable.c.y]).
where(table.c.x == othertable.c.x)
)
)

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

WHERE COL IN (SELECT othertable.y
FROM othertable WHERE othertable.x = table.x)
Parameters: other¶ – a list of literals, a select() construct, or a bindparam() construct that includes the bindparam.expanding flag set to True.
is_(other)

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.

New in version 0.7.9.

is_distinct_from(other)

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.

isnot(other)

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.

New in version 0.7.9.

isnot_distinct_from(other)

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

New in version 1.1.

like(other, escape=None)

Implement the like operator.

In a column context, produces the expression:

a LIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.like("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)

Implements a database-specific ‘match’ operator.

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

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)

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 create_engine.empty_in_strategy may be used to alter this behavior.

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

notlike(other, escape=None)

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()

Produce a nullsfirst() clause against the parent object.

nullslast()

Produce a nullslast() clause against the parent object.

of_type(class_)

Redefine this object in terms of a polymorphic subclass.

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

e.g.:

query.join(Company.employees.of_type(Engineer)).\
filter(Engineer.name=='foo')
Parameters: class_¶ – a class or mapper indicating that criterion will be against this specific subclass.
op(opstring, precedence=0, is_comparison=False, return_type=None)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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. New in version 0.8: - added the ‘precedence’ argument. 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 Operators.op.is_comparison 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 Operators.op.is_comparison will resolve to Boolean, and those that do not will be of the same type as the left-hand operand. New in version 1.2.0b3: - added the Operators.op.return_type argument.
operate(op, *other, **kwargs)
inherited from the operate() method of Operators

Operate on an argument.

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

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

class MyComparator(ColumnOperators):
def operate(self, op, other):
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().
reverse_operate(op, other, **kwargs)

Reverse operate on an argument.

Usage is the same as operate().

startswith(other, **kwargs)

Implement the startswith operator.

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

column LIKE <other> || '%'

E.g.:

stmt = select([sometable]).\
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 occurences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

Parameters: other¶ – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the 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: somecolumn.startswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.startswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.startswith.escape parameter. 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: somecolumn.startswith("foo/%bar", escape="^") Will render as: somecolumn LIKE :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.startswith.autoescape: 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.
class sqlalchemy.orm.properties.RelationshipProperty(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, post_update=False, cascade=False, extension=None, 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)

Bases: sqlalchemy.orm.interfaces.StrategizedProperty

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

Public constructor is the orm.relationship() function.

Relationship Configuration

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

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

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

PropComparator

ColumnProperty.Comparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

__eq__(other)

Implement the == operator.

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

MyClass.some_prop == <some object>

this will typically produce a clause such as:

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 contains().
• 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 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.
__init__(prop, parentmapper, adapt_to_entity=None, of_type=None)

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

__le__(other)

Implement the <= operator.

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

__lt__(other)

Implement the < operator.

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

__ne__(other)

Implement the != operator.

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

MyClass.some_prop != <some object>

This will typically produce a clause such as:

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 contains() in conjunction with not_().
• 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 has() in conjunction with not_() 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.
adapt_to_entity(adapt_to_entity)

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

adapter
inherited from the adapter attribute of PropComparator

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

all_()

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

# postgresql '5 = ALL (somearray)'
expr = 5 == mytable.c.somearray.all_()

# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().all_()

all_() - standalone version

any_() - ANY operator

New in version 1.1.

any(criterion=None, **kwargs)

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

An expression like:

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

Will produce a query like:

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

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

any() is particularly useful for testing for empty collections:

session.query(MyClass).filter(
~MyClass.somereference.any()
)

will produce:

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

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

any_()

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

# postgresql '5 = ANY (somearray)'
expr = 5 == mytable.c.somearray.any_()

# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().any_()

any_() - standalone version

all_() - ALL operator

New in version 1.1.

asc()

Produce a asc() clause against the parent object.

between(cleft, cright, symmetric=False)

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

bool_op(opstring, precedence=0)
inherited from the bool_op() method of Operators

Return a custom boolean operator.

This method is shorthand for calling Operators.op() and passing the Operators.op.is_comparison flag with True.

New in version 1.2.0b3.

collate(collation)

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

concat(other)

Implement the ‘concat’ operator.

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

contains(other, **kwargs)

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

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

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

MyClass.contains(other)

Produces a clause like:

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 contains() is very useful when used with simple one-to-many operations.

For many-to-many operations, the behavior of contains() 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:

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

Produces a query like:

SELECT * FROM my_table, my_association_table AS
my_association_table_1 WHERE
my_table.id = my_association_table_1.parent_id
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 contains() will not work with many-to-many collections when used in queries that move beyond simple AND conjunctions, such as multiple contains() expressions joined by OR. In such cases subqueries or explicit “outer joins” will need to be used instead. See any() for a less-performant alternative using EXISTS, or refer to Query.outerjoin() as well as Querying with Joins for more details on constructing outer joins.

desc()

Produce a desc() clause against the parent object.

distinct()

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)

Implement the ‘endswith’ operator.

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

column LIKE '%' || <other>

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.endswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.endswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.endswith.escape parameter. 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: somecolumn.endswith("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param ESCAPE '^' The parameter may also be combined with ColumnOperators.endswith.autoescape: 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.
has(criterion=None, **kwargs)

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

An expression like:

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

Will produce a query like:

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

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

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

ilike(other, escape=None)

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

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

lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

a ILIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.ilike("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.ilike("foo/%bar", escape="/")
in_(other)

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

is_(other)

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.

New in version 0.7.9.

is_distinct_from(other)

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.

isnot(other)

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.

New in version 0.7.9.

isnot_distinct_from(other)

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

New in version 1.1.

like(other, escape=None)

Implement the like operator.

In a column context, produces the expression:

a LIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.like("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.like("foo/%bar", escape="/")
mapper

The target Mapper referred to by this RelationshipProperty.Comparator.

This is the “target” or “remote” side of the relationship().

match(other, **kwargs)

Implements a database-specific ‘match’ operator.

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

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)

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 create_engine.empty_in_strategy may be used to alter this behavior.

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

notlike(other, escape=None)

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()

Produce a nullsfirst() clause against the parent object.

nullslast()

Produce a nullslast() clause against the parent object.

of_type(cls)

Redefine this object in terms of a polymorphic subclass.

See PropComparator.of_type() for an example.

op(opstring, precedence=0, is_comparison=False, return_type=None)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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. New in version 0.8: - added the ‘precedence’ argument. 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 Operators.op.is_comparison 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 Operators.op.is_comparison will resolve to Boolean, and those that do not will be of the same type as the left-hand operand. New in version 1.2.0b3: - added the Operators.op.return_type argument.
operate(op, *other, **kwargs)
inherited from the operate() method of Operators

Operate on an argument.

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

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

class MyComparator(ColumnOperators):
def operate(self, op, other):
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().
reverse_operate(op, other, **kwargs)

Reverse operate on an argument.

Usage is the same as operate().

startswith(other, **kwargs)

Implement the startswith operator.

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

column LIKE <other> || '%'

E.g.:

stmt = select([sometable]).\
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 occurences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

Parameters: other¶ – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the 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: somecolumn.startswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.startswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.startswith.escape parameter. 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: somecolumn.startswith("foo/%bar", escape="^") Will render as: somecolumn LIKE :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.startswith.autoescape: 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.
__init__(argument, secondary=None, primaryjoin=None, secondaryjoin=None, foreign_keys=None, uselist=None, order_by=False, backref=None, back_populates=None, post_update=False, cascade=False, extension=None, 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)

Construct a new RelationshipProperty object.

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

cascade

Return the current cascade setting for this RelationshipProperty.

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.

class_attribute

Return the class-bound descriptor corresponding to this MapperProperty.

This is basically a getattr() call:

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:

>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
True
True
create_row_processor(context, path, mapper, result, adapter, populators)
inherited from the create_row_processor() method of StrategizedProperty

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

do_init()

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

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

extension_type = symbol('NOT_EXTENSION')
init()

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

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

mapper

Return the targeted Mapper for this RelationshipProperty.

This is a lazy-initializing static attribute.

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.

post_instrument_class(mapper)
inherited from the 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.

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.

setup(context, entity, path, adapter, **kwargs)
inherited from the 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.

table

Return the selectable linked to this RelationshipProperty object’s target Mapper.

Deprecated since version 0.7: Use .target

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

Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty

__init__(name, map_column=None, descriptor=None, comparator_factory=None, doc=None, info=None)

Construct a new SynonymProperty object.

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

cascade_iterator(type_, state, visited_instances=None, 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.

class_attribute

Return the class-bound descriptor corresponding to this MapperProperty.

This is basically a getattr() call:

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:

>>> from sqlalchemy import inspect
>>> mapper = inspect(User)
True
True
create_row_processor(context, path, mapper, result, adapter, populators)

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

do_init()

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

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

extension_type = symbol('NOT_EXTENSION')
init()

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

instrument_class(mapper)
inherited from the 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).

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.

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.

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.

setup(context, 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.

class sqlalchemy.orm.query.QueryContext(query)
class sqlalchemy.orm.attributes.QueryableAttribute(class_, key, impl=None, comparator=None, parententity=None, of_type=None)

Bases: sqlalchemy.orm.base._MappedAttribute, sqlalchemy.orm.base.InspectionAttr, sqlalchemy.orm.interfaces.PropComparator

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

__eq__(other)

Implement the == operator.

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

__le__(other)

Implement the <= operator.

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

__lt__(other)

Implement the < operator.

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

__ne__(other)

Implement the != operator.

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

adapt_to_entity(adapt_to_entity)

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

adapter
inherited from the adapter attribute of PropComparator

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

all_()

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

# postgresql '5 = ALL (somearray)'
expr = 5 == mytable.c.somearray.all_()

# mysql '5 = ALL (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().all_()

all_() - standalone version

any_() - ANY operator

New in version 1.1.

any(criterion=None, **kwargs)

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

The usual implementation of any() is RelationshipProperty.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.
any_()

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

# postgresql '5 = ANY (somearray)'
expr = 5 == mytable.c.somearray.any_()

# mysql '5 = ANY (SELECT value FROM table)'
expr = 5 == select([table.c.value]).as_scalar().any_()

any_() - standalone version

all_() - ALL operator

New in version 1.1.

asc()

Produce a asc() clause against the parent object.

between(cleft, cright, symmetric=False)

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

bool_op(opstring, precedence=0)
inherited from the bool_op() method of Operators

Return a custom boolean operator.

This method is shorthand for calling Operators.op() and passing the Operators.op.is_comparison flag with True.

New in version 1.2.0b3.

collate(collation)

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

concat(other)

Implement the ‘concat’ operator.

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

contains(other, **kwargs)

Implement the ‘contains’ operator.

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

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

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.contains("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.contains.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.contains.escape parameter. 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: somecolumn.contains("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.contains.autoescape: 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.
desc()

Produce a desc() clause against the parent object.

distinct()

Produce a distinct() clause against the parent object.

endswith(other, **kwargs)

Implement the ‘endswith’ operator.

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

column LIKE '%' || <other>

E.g.:

stmt = select([sometable]).\
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 occurences 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 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: somecolumn.endswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE '%' || :param ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.endswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.endswith.escape parameter. 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: somecolumn.endswith("foo/%bar", escape="^") Will render as: somecolumn LIKE '%' || :param ESCAPE '^' The parameter may also be combined with ColumnOperators.endswith.autoescape: 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.
extension_type = symbol('NOT_EXTENSION')
has(criterion=None, **kwargs)

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

The usual implementation of has() is RelationshipProperty.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.
ilike(other, escape=None)

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

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

lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

a ILIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.ilike("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.ilike("foo/%bar", escape="/")
in_(other)

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

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:

WHERE COL IN (?, ?, ?)
• An empty list, e.g.:

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

In this calling form, the expression renders a “false” expression, e.g.:

WHERE 1 != 1

This “false” expression has historically had different behaviors in older SQLAlchemy versions, see create_engine.empty_in_strategy for behavioral options.

Changed in version 1.2: simplified the behavior of “empty in” expressions

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

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

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

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:

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

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

WHERE COL IN (?, ?, ?)

New in version 1.2: added “expanding” bound parameters

The “expanding” feature in version 1.2 of SQLAlchemy does not support passing an empty list as a parameter value; however, version 1.3 does support this.

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

stmt.where(
column.in_(
select([othertable.c.y]).
where(table.c.x == othertable.c.x)
)
)

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

WHERE COL IN (SELECT othertable.y
FROM othertable WHERE othertable.x = table.x)
Parameters: other¶ – a list of literals, a select() construct, or a bindparam() construct that includes the bindparam.expanding flag set to True.
info

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

The behavior here is as follows:

New in version 0.8.0.

is_(other)

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.

New in version 0.7.9.

is_distinct_from(other)

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.

isnot(other)

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.

New in version 0.7.9.

isnot_distinct_from(other)

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

New in version 1.1.

like(other, escape=None)

Implement the like operator.

In a column context, produces the expression:

a LIKE other

E.g.:

stmt = select([sometable]).\
where(sometable.c.column.like("%foobar%"))
Parameters: other¶ – expression to be compared escape¶ – optional escape character, renders the ESCAPE keyword, e.g.: somecolumn.like("foo/%bar", escape="/")
match(other, **kwargs)

Implements a database-specific ‘match’ operator.

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

implement the NOT ILIKE operator.

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

New in version 0.8.

notin_(other)

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 create_engine.empty_in_strategy may be used to alter this behavior.

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

notlike(other, escape=None)

implement the NOT LIKE operator.

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

New in version 0.8.

nullsfirst()

Produce a nullsfirst() clause against the parent object.

nullslast()

Produce a nullslast() clause against the parent object.

of_type(cls)

Redefine this object in terms of a polymorphic subclass.

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

e.g.:

query.join(Company.employees.of_type(Engineer)).\
filter(Engineer.name=='foo')
Parameters: class_¶ – a class or mapper indicating that criterion will be against this specific subclass.
op(opstring, precedence=0, is_comparison=False, return_type=None)
inherited from the op() method of Operators

produce a generic operator function.

e.g.:

somecolumn.op("*")(5)

produces:

somecolumn * 5

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

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. New in version 0.8: - added the ‘precedence’ argument. 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 Operators.op.is_comparison 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 Operators.op.is_comparison will resolve to Boolean, and those that do not will be of the same type as the left-hand operand. New in version 1.2.0b3: - added the Operators.op.return_type argument.
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:

class MyComparator(ColumnOperators):
def operate(self, op, other):
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().
parent

Return an inspection instance representing the parent.

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

property

Return the MapperProperty associated with this QueryableAttribute.

Return values here will commonly be instances of ColumnProperty or RelationshipProperty.

reverse_operate(op, other, **kwargs)

Reverse operate on an argument.

Usage is the same as operate().

startswith(other, **kwargs)

Implement the startswith operator.

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

column LIKE <other> || '%'

E.g.:

stmt = select([sometable]).\
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 occurences of these characters within the string value so that they match as themselves and not as wildcard characters. Alternatively, the ColumnOperators.startswith.escape parameter will establish a given character as an escape character which can be of use when the target expression is not a literal string.

Parameters: other¶ – expression to be compared. This is usually a plain string value, but can also be an arbitrary SQL expression. LIKE wildcard characters % and _ are not escaped by default unless the 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: somecolumn.startswith("foo%bar", autoescape=True) Will render as: somecolumn LIKE :param || '%' ESCAPE '/' With the value of :param as "foo/%bar". New in version 1.2. Changed in version 1.2.0: The ColumnOperators.startswith.autoescape parameter is now a simple boolean rather than a character; the escape character itself is also escaped, and defaults to a forwards slash, which itself can be customized using the ColumnOperators.startswith.escape parameter. 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: somecolumn.startswith("foo/%bar", escape="^") Will render as: somecolumn LIKE :param || '%' ESCAPE '^' The parameter may also be combined with ColumnOperators.startswith.autoescape: 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.
class sqlalchemy.orm.session.UOWTransaction(session)
filter_states_for_dep(dep, states)

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

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.

get_attribute_history(state, key, passive=symbol('PASSIVE_NO_INITIALIZE'))

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

is_deleted(state)

return true if the given state is marked as deleted within this uowtransaction.

remove_state_actions(state)

remove pending actions for a state from the uowtransaction.

was_already_deleted(state)

return true if the given state is expired and was deleted previously.

Previous: ORM Events Next: ORM Exceptions