ORM Internals

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

  • class sqlalchemy.orm.state.AttributeState(state, key)
  • Provide an inspection interface correspondingto a particular attribute on a particular mapped object.

The AttributeState object is accessedvia the InstanceState.attrs collectionof a particular InstanceState:

  1. from sqlalchemy import inspect
  2.  
  3. insp = inspect(some_mapped_object)
  4. attr_state = insp.attrs.some_attribute
  • property history
  • Return the current pre-flush change history forthis attribute, via the History interface.

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

Note

The attribute history system tracks changes on a per flushbasis. Each time the Session is flushed, the historyof each attribute is reset to empty. The Session bydefault autoflushes each time a Query is invoked. Foroptions on how to control this, see Flushing.

See also

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

attributes.get_history() - underlying function

  • load_history()
  • Return the current pre-flush change history forthis attribute, via the History interface.

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

Note

The attribute history system tracks changes on a per flushbasis. Each time the Session is flushed, the historyof each attribute is reset to empty. The Session bydefault autoflushes each time a Query is invoked. Foroptions on how to control this, see Flushing.

See also

AttributeState.history

attributes.get_history() - underlying function

New in version 0.9.0.

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

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

  • property value
  • Return the value of this attribute.

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

  • class sqlalchemy.orm.util.CascadeOptions
  • Bases: builtins.frozenset

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

  • class sqlalchemy.orm.instrumentation.ClassManager(class_)
  • Bases: builtins.dict

tracks state information at the class level.

  • le()

inherited from the le() method of dict

Return self<=value.

  • lt()

inherited from the lt() method of dict

Return selfne()="" -="" inherited="" from="" the="" ne()="" method="" of="" dict="" return="" self!="value." -="" 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()="" -="" inherited="" from="" the="" fromkeys()="" method="" of="" dict="" create="" a="" new="" dictionary="" with="" keys="" from="" iterable="" and="" values="" set="" to="" value.="" -="" get()="" -="" inherited="" from="" the="" get()="" method="" of="" dict="" return="" the="" value="" for="" key="" if="" key="" is="" in="" the="" dictionary,="" else="" default.="" -="" hasparent(_state,="" key,="" optimistic="False)" -="" todo="" -="" items()="" →="" a="" set-like="" object="" providing="" a="" view="" on="" d's="" items="" -="" inherited="" from="" the="" items()="" method="" of="" dict="" -="" keys()="" →="" a="" set-like="" object="" providing="" a="" view="" on="" d's="" keys="" -="" inherited="" from="" the="" keys()="" method="" of="" dict="" -="" manage()="" -="" mark="" this="" instance="" as="" the="" manager="" for="" its="" class.="" -="" originalinit()="" -="" initialize="" self.="" see="" help(type(self))="" for="" accurate="" 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()="" -="" inherited="" from="" the="" setdefault()="" method="" of="" dict="" insert="" key="" with="" a="" value="" of="" default="" if="" key="" is="" not="" in="" the="" dictionary.="" return="" the="" value="" for="" key="" if="" key="" is="" in="" the="" dictionary,="" else="" default.="" -="" state_getter()="" -="" return="" a="" (instance)="" -=""> InstanceState callable.

“state getter” callables should raise either KeyError orAttributeError if no InstanceState could be found for theinstance.

  • 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 is present and has a .keys() method, then does: for k in E: D[k] = E[k]If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = vIn either case, this is followed by: for k in F: D[k] = F[k]

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

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

Produce boolean, comparison, and other operators forColumnProperty attributes.

See the documentation for PropComparator for a briefoverview.

See also

PropComparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

  1. - <code>__eq__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.__eq__)
  2. -

inherited from theeq()method ofColumnOperators

Implement the == operator.

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

  1. - <code>__le__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.__le__)
  2. -

inherited from thele()method ofColumnOperators

Implement the <= operator.

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

  1. - <code>__lt__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.__lt__)
  2. -

inherited from thelt()method ofColumnOperators

Implement the < operator.

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

  1. - <code>__ne__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.__ne__)
  2. -

inherited from thene()method ofColumnOperators

Implement the != operator.

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

  1. - <code>adapt_to_entity</code>(_adapt_to_entity_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.adapt_to_entity)
  2. -

inherited from theadapt_to_entity()method ofPropComparator

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

  1. - _property _<code>adapter</code>[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.adapter)
  2. -

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

  1. - <code>all_</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.all_)
  2. -

inherited from theall_()method ofColumnOperators

Produce a all_() clause against theparent object.

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

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

See also

all_() - standalone version

any_() - ANY operator

New in version 1.1.

  1. - <code>any</code>(_criterion=None_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.any)
  2. -

inherited from theany()method ofPropComparator

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

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

  1. - Parameters
  2. -
  3. -

criterion – an optional ClauseElement formulated against themember class’ table or attributes.

  1. -

**kwargs – key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values.

  1. - <code>any_</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.any_)
  2. -

inherited from theany_()method ofColumnOperators

Produce a any_() clause against theparent object.

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

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

See also

any_() - standalone version

all_() - ALL operator

New in version 1.1.

  1. - <code>asc</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.asc)
  2. -

inherited from theasc()method ofColumnOperators

Produce a asc() clause against theparent object.

  1. - <code>between</code>(_cleft_, _cright_, _symmetric=False_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.between)
  2. -

inherited from thebetween()method ofColumnOperators

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

  1. - <code>bool_op</code>(_opstring_, _precedence=0_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.bool_op)
  2. -

inherited from thebool_op()method ofOperators

Return a custom boolean operator.

This method is shorthand for callingOperators.op() and passing theOperators.op.is_comparisonflag with True.

New in version 1.2.0b3.

See also

Operators.op()

  1. - <code>collate</code>(_collation_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.collate)
  2. -

inherited from thecollate()method ofColumnOperators

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

See also

collate()

  1. - <code>concat</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.concat)
  2. -

inherited from theconcat()method ofColumnOperators

Implement the ‘concat’ operator.

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

  1. - <code>contains</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.contains)
  2. -

inherited from thecontains()method ofColumnOperators

Implement the ‘contains’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.contains.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.contains.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.contains.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.contains.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.endswith()

ColumnOperators.like()

  1. - <code>desc</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.desc)
  2. -

inherited from thedesc()method ofColumnOperators

Produce a desc() clause against theparent object.

  1. - <code>distinct</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.distinct)
  2. -

inherited from thedistinct()method ofColumnOperators

Produce a distinct() clause against theparent object.

  1. - <code>endswith</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.endswith)
  2. -

inherited from theendswith()method ofColumnOperators

Implement the ‘endswith’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.endswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.endswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.endswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.endswith.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.contains()

ColumnOperators.like()

  1. - <code>has</code>(_criterion=None_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.has)
  2. -

inherited from thehas()method ofPropComparator

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

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

  1. - Parameters
  2. -
  3. -

criterion – an optional ClauseElement formulated against themember class’ table or attributes.

  1. -

**kwargs – key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values.

  1. - <code>ilike</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.ilike)
  2. -

inherited from theilike()method ofColumnOperators

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

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

  1. lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

  1. a ILIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.ilike("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.like()

  1. - <code>in_</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.in_)
  2. -

inherited from thein_()method ofColumnOperators

Implement the in operator.

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

The given parameter other may be:

  1. -

A list of literal values, e.g.:

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

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

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

A list of tuples may be provided if the comparison is against atuple_() containing multiple expressions:

  1. from sqlalchemy import tuple_
  2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
  1. -

An empty list, e.g.:

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

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

  1. WHERE 1 != 1

This “false” expression has historically had different behaviorsin older SQLAlchemy versions, seecreate_engine.empty_in_strategy for behavioral options.

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

  1. -

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

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

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

  1. WHERE COL IN ([EXPANDING_value])

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

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

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

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

New in version 1.2: added “expanding” bound parameters

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

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

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

  1. -

a select() construct, which is usually a correlatedscalar select:

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

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

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

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

  1. - <code>is_</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.is_)
  2. -

inherited from theis_()method ofColumnOperators

Implement the IS operator.

Normally, IS is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.isnot()

  1. - <code>is_distinct_from</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.is_distinct_from)
  2. -

inherited from theis_distinct_from()method ofColumnOperators

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.

  1. - <code>isnot</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.isnot)
  2. -

inherited from theisnot()method ofColumnOperators

Implement the IS NOT operator.

Normally, IS NOT is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS NOT may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.is_()

  1. - <code>isnot_distinct_from</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.isnot_distinct_from)
  2. -

inherited from theisnot_distinct_from()method ofColumnOperators

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.

  1. - <code>like</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.like)
  2. -

inherited from thelike()method ofColumnOperators

Implement the like operator.

In a column context, produces the expression:

  1. a LIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.like("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.ilike()

  1. - <code>match</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.match)
  2. -

inherited from thematch()method ofColumnOperators

Implements a database-specific ‘match’ operator.

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

  1. -

PostgreSQL - renders x @@ to_tsquery(y)

  1. -

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

  1. -

Oracle - renders CONTAINS(x, y)

  1. -

other backends may provide special implementations.

  1. -

Backends without any special implementation will emitthe operator as “MATCH”. This is compatible with SQLite, forexample.

  1. - <code>notilike</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.notilike)
  2. -

inherited from thenotilike()method ofColumnOperators

implement the NOT ILIKE operator.

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

See also

ColumnOperators.ilike()

  1. - <code>notin_</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.notin_)
  2. -

inherited from thenotin_()method ofColumnOperators

implement the NOT IN operator.

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

In the case that other is an empty sequence, the compilerproduces an “empty not in” expression. This defaults to theexpression “1 = 1” to produce true in all cases. Thecreate_engine.empty_in_strategy may be used toalter this behavior.

Changed in version 1.2: The ColumnOperators.in_() andColumnOperators.notin_() operatorsnow produce a “static” expression for an empty IN sequenceby default.

See also

ColumnOperators.in_()

  1. - <code>notlike</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.notlike)
  2. -

inherited from thenotlike()method ofColumnOperators

implement the NOT LIKE operator.

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

See also

ColumnOperators.like()

  1. - <code>nullsfirst</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.nullsfirst)
  2. -

inherited from thenullsfirst()method ofColumnOperators

Produce a nullsfirst() clause against theparent object.

  1. - <code>nullslast</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.nullslast)
  2. -

inherited from thenullslast()method ofColumnOperators

Produce a nullslast() clause against theparent object.

  1. - <code>of_type</code>(_class__)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.of_type)
  2. -

inherited from theof_type()method ofPropComparator

Redefine this object in terms of a polymorphic subclass.

Returns a new PropComparator from which further criterion can beevaluated.

e.g.:

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

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

See also

Referring to specific subtypes on relationships

  1. - <code>op</code>(_opstring_, _precedence=0_, _is_comparison=False_, _return_type=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.op)
  2. -

inherited from theop()method ofOperators

produce a generic operator function.

e.g.:

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

produces:

  1. somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

  1. - Parameters
  2. -
  3. -

operator – a string which will be output as the infix operatorbetween this element and the expression passed to thegenerated function.

  1. -

precedence – precedence to apply to the operator, whenparenthesizing expressions. A lower number will cause the expressionto be parenthesized when applied against another operator withhigher precedence. The default value of 0 is lower than alloperators except for the comma (,) and AS operators.A value of 100 will be higher or equal to all operators, and -100will be lower than or equal to all operators.

  1. -

is_comparison

if True, the operator will be considered as a“comparison” operator, that is which evaluates to a booleantrue/false value, like ==, >, etc. This flag should be setso that ORM relationships can establish that the operator is acomparison operator when used in a custom join condition.

New in version 0.9.2: - added theOperators.op.is_comparison flag.

  1. -

return_type

a TypeEngine class or object that willforce the return type of an expression produced by this operatorto be of that type. By default, operators that specifyOperators.op.is_comparison will resolve toBoolean, and those that do not will be of the sametype as the left-hand operand.

New in version 1.2.0b3: - added theOperators.op.return_type argument.

See also

Redefining and Creating New Operators

Using custom operators in join conditions

  1. - <code>operate</code>(_op_, _*other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.operate)
  2. -

Operate on an argument.

This is the lowest level of operation, raisesNotImplementedError by default.

Overriding this on a subclass can allow commonbehavior to be applied to all operations.For example, overriding ColumnOperatorsto apply func.lower() to the left and rightside:

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

op – Operator callable.

  1. -

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

  1. -

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

  1. - <code>reverse_operate</code>(_op_, _other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.reverse_operate)
  2. -

Reverse operate on an argument.

Usage is the same as operate().

  1. - <code>startswith</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.ColumnProperty.Comparator.startswith)
  2. -

inherited from thestartswith()method ofColumnOperators

Implement the startswith operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.startswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.startswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.startswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.startswith.autoescape:

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

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

See also

ColumnOperators.endswith()

ColumnOperators.contains()

ColumnOperators.like()

  • eq()

inherited from the eq() method of object

Return self==value.

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

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.orm.properties.ComparableProperty(comparator_factory, descriptor=None, doc=None, info=None)
  • Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty

Deprecated since version 0.7: comparable_property() is deprecated and will be removed in a future release. Please refer to the hybrid extension.

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.descriptorprops.CompositeProperty(class_, attrs, *kwargs_)
  • Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty

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

CompositeProperty is constructed using the composite()function.

See also

Composite Column Types

Produce boolean, comparison, and other operators forCompositeProperty attributes.

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

See also

PropComparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

  • class CompositeBundle(property__, _expr)
  • Bases: sqlalchemy.orm.query.Bundle

    • createrow_processor(_query, procs, labels)
    • Produce the “row processing” function for this Bundle.

May be overridden by subclasses.

See also

Column Bundles - includes an example of subclassing.

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 CompositePropertyhas been associated with its parent mapper.

  • gethistory(_state, dict__, _passive=symbol('PASSIVE_OFF'))

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

  • instrumentclass(_mapper)

  • Hook called by the Mapper to the property to initiateinstrumentation of the class attribute managed by thisMapperProperty.

The MapperProperty here will typically call out to theattributes 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 theMapperProperty has determined what kind of persistencemanagement 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 attributeevents.

Serves as an indicator of the source of the event and also providesa means of controlling propagation across a chain of attributeoperations.

The Event object is sent as the initiator argumentwhen dealing with events such as AttributeEvents.append(),AttributeEvents.set(),and AttributeEvents.remove().

The Event object is currently interpreted by the backrefevent handlers, and is used to control the propagation of operationsacross two mutually-dependent attributes.

New in version 0.9.0.

  • Variables
    • impl – The AttributeImpl which is the current eventinitiator.

    • op – The symbol OP_APPEND, OP_REMOVE,OP_REPLACE, or OP_BULK_REPLACE, indicating thesource operation.

  • class sqlalchemy.orm.identity.IdentityMap
    • check_modified()
    • return True if any InstanceStates present have been markedas ‘modified’.
  • class sqlalchemy.orm.base.InspectionAttr

  • A base class applied to all ORM objects that can be returnedby the inspect() function.

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

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

See also

HYBRID_METHOD

HYBRID_PROPERTY

ASSOCIATION_PROXY

  • isaliased_class = False_
  • True if this object is an instance of AliasedClass.

  • isattribute = False_

  • True if this object is a Python descriptor.

This can refer to one of many types. Usually aQueryableAttribute which handles attributes events on behalfof a MapperProperty. But can also be an extension typesuch as AssociationProxy or hybrid_property.The InspectionAttr.extension_type will refer to a constantidentifying the specific subtype.

See also

Mapper.all_orm_descriptors

  • isclause_element = False_
  • True if this object is an instance of ClauseElement.

  • isinstance = False_

  • True if this object is an instance of InstanceState.

  • ismapper = False_

  • True if this object is an instance of Mapper.

  • isproperty = False_

  • True if this object is an instance of MapperProperty.

  • isselectable = False_

  • Return True if this object is an instance of Selectable.

Adds the .info attribute to InspectionAttr.

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

  • info
  • Info dictionary associated with the object, allowing user-defineddata to be associated with this InspectionAttr.

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

Changed in version 1.0.0: MapperProperty.info is alsoavailable on extension types via theInspectionAttrInfo.info attribute, so that it can applyto a wider variety of ORM and extension constructs.

See also

QueryableAttribute.info

SchemaItem.info

tracks state information at the instance level.

The InstanceState is a key object used by theSQLAlchemy ORM in order to track the state of an object;it is created the moment an object is instantiated, typicallyas a result of instrumentation which SQLAlchemy appliesto the init() method of the class.

InstanceState is also a semi-public object,available for runtime inspection as to the state of amapped instance, including information such as its currentstatus within a particular Session and detailsabout data on individual attributes. The public APIin order to acquire a InstanceState objectis to use the inspect() system:

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

See also

Runtime Inspection API

  • attrs
  • Return a namespace representing each attribute onthe mapped object, including its current valueand history.

The returned object is an instance of AttributeState.This object allows inspection of the current datawithin an attribute as well as attribute historysince 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 / deferredloaders that were set up via query option.

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

  • property deleted
  • Return true if the object is deleted.

An object that is in the deleted state is guaranteed tonot be within the Session.identity_map of its parentSession; however if the session’s transaction is rolledback, the object will be restored to the persistent state andthe identity map.

Note

The InstanceState.deleted attribute refers to a specificstate of the object that occurs between the “persistent” and“detached” states; once the object is detached, theInstanceState.deleted attribute no longer returnsTrue; in order to detect that a state was deleted, regardlessof whether or not the object is associated with aSession, use the InstanceState.was_deletedaccessor.

See also

Quickie Intro to Object States

  • property detached
  • Return true if the object is detached.

See also

Quickie Intro to Object States

  • property dict
  • Return the instance dict used by the object.

Under normal circumstances, this is always synonymouswith the dict attribute of the mapped object,unless an alternative instrumentation system has beenconfigured.

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

  • expiredattributes = None_
  • The set of keys which are ‘expired’ to be loaded bythe manager’s deferred scalar loader, assuming no pendingchanges.

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

  • property has_identity
  • Return True if this object has an identity key.

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

  • property identity
  • Return the mapped identity of the mapped object.This is the primary key identity as persisted by the ORMwhich can always be passed directly toQuery.get().

Returns None if the object has no primary key identity.

Note

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

  • property identity_key
  • Return the identity key for the mapped object.

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

  • mapper
  • Return the Mapper used for this mapped object.

  • property object

  • Return the mapped object represented by thisInstanceState.

  • property pending

  • Return true if the object is pending.

See also

Quickie Intro to Object States

  • property persistent
  • Return true if the object is persistent.

An object that is in the persistent state is guaranteed tobe within the Session.identity_map of its parentSession.

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

See also

Quickie Intro to Object States

  • property 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 deletedwill report as not in session, however if the transaction isstill in progress, this attribute will still refer to that session.Only when the transaction is completed does the object becomefully detached under normal circumstances.

  • property transient
  • Return true if the object is transient.

See also

Quickie Intro to Object States

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

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

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

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

  • property unmodified
  • Return the set of keys which have no uncommitted changes

  • unmodifiedintersection(_keys)

  • Return self.unmodified.intersection(keys).

  • property 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 explicitlyor 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 oform.util.was_deleted().

See also

InstanceState.deleted - refers to the “deleted” state

orm.util.was_deleted() - standalone function

Quickie Intro to Object States

Class bound instrumented attribute which adds basicdescriptor 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 withincertain 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 withincertain API features.

Represent a particular class attribute mapped by Mapper.

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

  • info
  • Info dictionary associated with the object, allowing user-defineddata to be associated with this InspectionAttr.

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

Changed in version 1.0.0: InspectionAttr.info movedfrom MapperProperty so that it can apply to a widervariety of ORM and extension constructs.

See also

QueryableAttribute.info

SchemaItem.info

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

  • cascadeiterator(type_, _state, visited_instances=None, halt_on=None)
  • Iterate through instances related to the given instance fora particular ‘cascade’, starting with this MapperProperty.

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

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

This method typically only applies to RelationshipProperty.

  • property class_attribute
  • Return the class-bound descriptor corresponding to thisMapperProperty.

This is basically a getattr() call:

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

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

  1. >>> from sqlalchemy import inspect
  2. >>> mapper = inspect(User)
  3. >>> addresses_property = mapper.attrs.addresses
  4. >>> addresses_property.class_attribute is User.addresses
  5. True
  6. >>> User.addresses.property is addresses_property
  7. True
  • createrow_processor(_context, path, mapper, result, adapter, populators)
  • Produce row processing functions and append to the givenset of populators lists.

  • do_init()

  • Perform subclass-specific initialization post-mapper-creationsteps.

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

  • init()
  • Called after all mappers are created to assemblerelationships between mappers and perform other post-mapper-creationinitialization steps.

  • instrumentclass(_mapper)

  • Hook called by the Mapper to the property to initiateinstrumentation of the class attribute managed by thisMapperProperty.

The MapperProperty here will typically call out to theattributes 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 theMapperProperty has determined what kind of persistencemanagement it needs to do (e.g. scalar, object, collection, etc).

  • isproperty = True_
  • Part of the InspectionAttr interface; states this object is amapper property.

  • merge(session, source_state, source_dict, dest_state, dest_dict, load, recursive_, resolveconflict_map)

  • Merge the attribute represented by this MapperPropertyfrom source to destination object.

  • postinstrument_class(_mapper)

  • Perform instrumentation adjustments that need to occurafter init() has completed.

The given Mapper is the Mapper invoking the operation, whichmay not be the same Mapper as self.parent in an inheritancescenario; however, Mapper will always at least be a sub-mapper ofself.parent.

This method is typically used by StrategizedProperty, which delegatesit to LoaderStrategy.init_class_attribute() to perform final setupon the class-bound InstrumentedAttribute.

  • setparent(_parent, init)
  • Set the parent mapper that references this MapperProperty.

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

  • setup(context, query_entity, path, adapter, **kwargs)
  • Called by Query for the purposes of constructing a SQL statement.

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

  • sqlalchemy.orm.interfaces.NOTEXTENSION = symbol('NOTEXTENSION')
  • Symbol indicating an InspectionAttr that’snot part of sqlalchemy.ext.

Is assigned to the InspectionAttr.extension_typeattribute.

  • 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 withincertain API features.

Defines SQL operators for MapperProperty objects.

SQLAlchemy allows for operators tobe redefined at both the Core and ORM level. PropComparatoris 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 SQLAlchemy0.7, as well as Core-level operator redefinition inSQLAlchemy 0.8, the use case for user-defined PropComparatorinstances is extremely rare. See Hybrid Attributes as wellas Redefining and Creating New Operators.

User-defined subclasses of PropComparator may be created. Thebuilt-in Python comparison and math operator methods, such asoperators.ColumnOperators.eq(),operators.ColumnOperators.lt(), andoperators.ColumnOperators.add(), can be overridden to providenew operator behavior. The custom PropComparator is passed tothe MapperProperty instance via the comparator_factoryargument. In each case,the appropriate subclass of PropComparator should be used:

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

Note that for column-level operator redefinition, it’s usuallysimpler to define the operators at the Core level, using theTypeEngine.comparator_factory attribute. SeeRedefining and Creating New Operators for more detail.

See also

ColumnProperty.Comparator

RelationshipProperty.Comparator

CompositeProperty.Comparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

  • eq(other)

inherited from theeq()method ofColumnOperators

Implement the == operator.

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

  • le(other)

inherited from thele()method ofColumnOperators

Implement the <= operator.

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

  • lt(other)

inherited from thelt()method ofColumnOperators

Implement the < operator.

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

  • ne(other)

inherited from thene()method ofColumnOperators

Implement the != operator.

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

inherited from theall_()method ofColumnOperators

Produce a all_() clause against theparent object.

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

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

See also

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 thegiven criterion.

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

  1. - Parameters
  2. -
  3. -

criterion – an optional ClauseElement formulated against themember class’ table or attributes.

  1. -

**kwargs – key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values.

inherited from theany_()method ofColumnOperators

Produce a any_() clause against theparent object.

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

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

See also

any_() - standalone version

all_() - ALL operator

New in version 1.1.

  • asc()

inherited from theasc()method ofColumnOperators

Produce a asc() clause against theparent object.

  • between(cleft, cright, symmetric=False)

inherited from thebetween()method ofColumnOperators

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

  • boolop(_opstring, precedence=0)

inherited from thebool_op()method ofOperators

Return a custom boolean operator.

This method is shorthand for callingOperators.op() and passing theOperators.op.is_comparisonflag with True.

New in version 1.2.0b3.

See also

Operators.op()

  • collate(collation)

inherited from thecollate()method ofColumnOperators

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

See also

collate()

  • concat(other)

inherited from theconcat()method ofColumnOperators

Implement the ‘concat’ operator.

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

  • contains(other, **kwargs)

inherited from thecontains()method ofColumnOperators

Implement the ‘contains’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.contains.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.contains.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.contains.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.contains.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.endswith()

ColumnOperators.like()

  • desc()

inherited from thedesc()method ofColumnOperators

Produce a desc() clause against theparent object.

  • distinct()

inherited from thedistinct()method ofColumnOperators

Produce a distinct() clause against theparent object.

  • endswith(other, **kwargs)

inherited from theendswith()method ofColumnOperators

Implement the ‘endswith’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.endswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.endswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.endswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.endswith.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.contains()

ColumnOperators.like()

  • has(criterion=None, **kwargs)
  • Return true if this element references a member which meets thegiven criterion.

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

  1. - Parameters
  2. -
  3. -

criterion – an optional ClauseElement formulated against themember class’ table or attributes.

  1. -

**kwargs – key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values.

  • ilike(other, escape=None)

inherited from theilike()method ofColumnOperators

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

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

  1. lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

  1. a ILIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.ilike("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.like()

  • in(_other)

inherited from thein_()method ofColumnOperators

Implement the in operator.

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

The given parameter other may be:

  1. -

A list of literal values, e.g.:

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

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

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

A list of tuples may be provided if the comparison is against atuple_() containing multiple expressions:

  1. from sqlalchemy import tuple_
  2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
  1. -

An empty list, e.g.:

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

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

  1. WHERE 1 != 1

This “false” expression has historically had different behaviorsin older SQLAlchemy versions, seecreate_engine.empty_in_strategy for behavioral options.

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

  1. -

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

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

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

  1. WHERE COL IN ([EXPANDING_value])

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

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

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

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

New in version 1.2: added “expanding” bound parameters

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

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

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

  1. -

a select() construct, which is usually a correlatedscalar select:

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

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

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

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

  • is(_other)

inherited from theis_()method ofColumnOperators

Implement the IS operator.

Normally, IS is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.isnot()

  • isdistinct_from(_other)

inherited from theis_distinct_from()method ofColumnOperators

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)

inherited from theisnot()method ofColumnOperators

Implement the IS NOT operator.

Normally, IS NOT is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS NOT may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.is_()

  • isnotdistinct_from(_other)

inherited from theisnot_distinct_from()method ofColumnOperators

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)

inherited from thelike()method ofColumnOperators

Implement the like operator.

In a column context, produces the expression:

  1. a LIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.like("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.ilike()

  • match(other, **kwargs)

inherited from thematch()method ofColumnOperators

Implements a database-specific ‘match’ operator.

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

  1. -

PostgreSQL - renders x @@ to_tsquery(y)

  1. -

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

  1. -

Oracle - renders CONTAINS(x, y)

  1. -

other backends may provide special implementations.

  1. -

Backends without any special implementation will emitthe operator as “MATCH”. This is compatible with SQLite, forexample.

  • notilike(other, escape=None)

inherited from thenotilike()method ofColumnOperators

implement the NOT ILIKE operator.

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

See also

ColumnOperators.ilike()

  • notin(_other)

inherited from thenotin_()method ofColumnOperators

implement the NOT IN operator.

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

In the case that other is an empty sequence, the compilerproduces an “empty not in” expression. This defaults to theexpression “1 = 1” to produce true in all cases. Thecreate_engine.empty_in_strategy may be used toalter this behavior.

Changed in version 1.2: The ColumnOperators.in_() andColumnOperators.notin_() operatorsnow produce a “static” expression for an empty IN sequenceby default.

See also

ColumnOperators.in_()

  • notlike(other, escape=None)

inherited from thenotlike()method ofColumnOperators

implement the NOT LIKE operator.

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

See also

ColumnOperators.like()

  • nullsfirst()

inherited from thenullsfirst()method ofColumnOperators

Produce a nullsfirst() clause against theparent object.

  • nullslast()

inherited from thenullslast()method ofColumnOperators

Produce a nullslast() clause against theparent object.

  • oftype(class)
  • Redefine this object in terms of a polymorphic subclass.

Returns a new PropComparator from which further criterion can beevaluated.

e.g.:

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

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

See also

Referring to specific subtypes on relationships

  • op(opstring, precedence=0, is_comparison=False, return_type=None)

inherited from theop()method ofOperators

produce a generic operator function.

e.g.:

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

produces:

  1. somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

  1. - Parameters
  2. -
  3. -

operator – a string which will be output as the infix operatorbetween this element and the expression passed to thegenerated function.

  1. -

precedence – precedence to apply to the operator, whenparenthesizing expressions. A lower number will cause the expressionto be parenthesized when applied against another operator withhigher precedence. The default value of 0 is lower than alloperators except for the comma (,) and AS operators.A value of 100 will be higher or equal to all operators, and -100will be lower than or equal to all operators.

  1. -

is_comparison

if True, the operator will be considered as a“comparison” operator, that is which evaluates to a booleantrue/false value, like ==, >, etc. This flag should be setso that ORM relationships can establish that the operator is acomparison operator when used in a custom join condition.

New in version 0.9.2: - added theOperators.op.is_comparison flag.

  1. -

return_type

a TypeEngine class or object that willforce the return type of an expression produced by this operatorto be of that type. By default, operators that specifyOperators.op.is_comparison will resolve toBoolean, and those that do not will be of the sametype as the left-hand operand.

New in version 1.2.0b3: - added theOperators.op.return_type argument.

See also

Redefining and Creating New Operators

Using custom operators in join conditions

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

inherited from theoperate()method ofOperators

Operate on an argument.

This is the lowest level of operation, raisesNotImplementedError by default.

Overriding this on a subclass can allow commonbehavior to be applied to all operations.For example, overriding ColumnOperatorsto apply func.lower() to the left and rightside:

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

op – Operator callable.

  1. -

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

  1. -

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

  • reverseoperate(_op, other, **kwargs)

inherited from thereverse_operate()method ofOperators

Reverse operate on an argument.

Usage is the same as operate().

  • startswith(other, **kwargs)

inherited from thestartswith()method ofColumnOperators

Implement the startswith operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.startswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.startswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.startswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.startswith.autoescape:

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

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

See also

ColumnOperators.endswith()

ColumnOperators.contains()

ColumnOperators.like()

  • 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, omit_join=None)
  • Bases: sqlalchemy.orm.interfaces.StrategizedProperty

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

Public constructor is the orm.relationship() function.

See also

Relationship Configuration

Produce boolean, comparison, and other operators forRelationshipProperty attributes.

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

See also

PropComparator

ColumnProperty.Comparator

ColumnOperators

Redefining and Creating New Operators

TypeEngine.comparator_factory

  1. - <code>__eq__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.__eq__)
  2. -

Implement the == operator.

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

  1. MyClass.some_prop == <some object>

this will typically produce aclause such as:

  1. mytable.related_id == <some id>

Where <some id> is the primary key of the givenobject.

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

  1. -

Comparisons against collections are not supported.Use contains().

  1. -

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

  1. -

Compared to a scalar many-to-many, an aliasof the association table will be rendered aswell, forming a natural join that is part of themain body of the query. This will not work forqueries that go beyond simple AND conjunctions ofcomparisons, such as those which use OR. Useexplicit joins, outerjoins, orhas() formore comprehensive non-many-to-one scalarmembership tests.

  1. -

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

  1. - <code>__init__</code>(_prop_, _parentmapper_, _adapt_to_entity=None_, _of_type=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.__init__)
  2. -

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

  1. - <code>__le__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.__le__)
  2. -

inherited from thele()method ofColumnOperators

Implement the <= operator.

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

  1. - <code>__lt__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.__lt__)
  2. -

inherited from thelt()method ofColumnOperators

Implement the < operator.

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

  1. - <code>__ne__</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.__ne__)
  2. -

Implement the != operator.

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

  1. MyClass.some_prop != <some object>

This will typically produce a clause such as:

  1. mytable.related_id != <some id>

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

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

  1. -

Comparisons against collections are not supported.Usecontains()in conjunction with not_().

  1. -

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

  1. -

Compared to a scalar many-to-many, an aliasof the association table will be rendered aswell, forming a natural join that is part of themain body of the query. This will not work forqueries that go beyond simple AND conjunctions ofcomparisons, such as those which use OR. Useexplicit joins, outerjoins, orhas() inconjunction with not_() formore comprehensive non-many-to-one scalarmembership tests.

  1. -

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

  1. - <code>adapt_to_entity</code>(_adapt_to_entity_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.adapt_to_entity)
  2. -

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

  1. - _property _<code>adapter</code>[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.adapter)
  2. -

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

  1. - <code>all_</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.all_)
  2. -

inherited from theall_()method ofColumnOperators

Produce a all_() clause against theparent object.

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

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

See also

all_() - standalone version

any_() - ANY operator

New in version 1.1.

  1. - <code>any</code>(_criterion=None_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.any)
  2. -

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

An expression like:

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

Will produce a query like:

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

Because any() usesa correlated subquery, its performance is not nearly asgood when compared against large target tables as that ofusing a join.

any() is particularlyuseful for testing for empty collections:

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

will produce:

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

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

  1. - <code>any_</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.any_)
  2. -

inherited from theany_()method ofColumnOperators

Produce a any_() clause against theparent object.

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

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

See also

any_() - standalone version

all_() - ALL operator

New in version 1.1.

  1. - <code>asc</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.asc)
  2. -

inherited from theasc()method ofColumnOperators

Produce a asc() clause against theparent object.

  1. - <code>between</code>(_cleft_, _cright_, _symmetric=False_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.between)
  2. -

inherited from thebetween()method ofColumnOperators

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

  1. - <code>bool_op</code>(_opstring_, _precedence=0_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.bool_op)
  2. -

inherited from thebool_op()method ofOperators

Return a custom boolean operator.

This method is shorthand for callingOperators.op() and passing theOperators.op.is_comparisonflag with True.

New in version 1.2.0b3.

See also

Operators.op()

  1. - <code>collate</code>(_collation_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.collate)
  2. -

inherited from thecollate()method ofColumnOperators

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

See also

collate()

  1. - <code>concat</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.concat)
  2. -

inherited from theconcat()method ofColumnOperators

Implement the ‘concat’ operator.

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

  1. - <code>contains</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.contains)
  2. -

Return a simple expression that tests a collection forcontainment of a particular item.

contains() isonly valid for a collection, i.e. arelationship() that implementsone-to-many or many-to-many with uselist=True.

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

  1. MyClass.contains(other)

Produces a clause like:

  1. mytable.id == <some id>

Where <some id> is the value of the foreign keyattribute on other which refers to the primarykey of its parent object. From this it follows thatcontains() isvery useful when used with simple one-to-manyoperations.

For many-to-many operations, the behavior ofcontains()has more caveats. The association table will berendered in the statement, producing an “implicit”join, that is, includes multiple tables in the FROMclause which are equated in the WHERE clause:

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

Produces a query like:

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

Where <some id> would be the primary key ofother. From the above, it is clear thatcontains()will not work with many-to-many collections whenused in queries that move beyond simple ANDconjunctions, such as multiplecontains()expressions joined by OR. In such cases subqueries orexplicit “outer joins” will need to be used instead.See any() fora less-performant alternative using EXISTS, or referto Query.outerjoin() as well as Querying with Joinsfor more details on constructing outer joins.

  1. - <code>desc</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.desc)
  2. -

inherited from thedesc()method ofColumnOperators

Produce a desc() clause against theparent object.

  1. - <code>distinct</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.distinct)
  2. -

inherited from thedistinct()method ofColumnOperators

Produce a distinct() clause against theparent object.

  1. - <code>endswith</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.endswith)
  2. -

inherited from theendswith()method ofColumnOperators

Implement the ‘endswith’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.endswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.endswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.endswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.endswith.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.contains()

ColumnOperators.like()

  1. - <code>entity</code>[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.entity)
  2. -

The target entity referred to by thisRelationshipProperty.Comparator.

This is either a Mapper or AliasedInspobject.

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

  1. - <code>has</code>(_criterion=None_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.has)
  2. -

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

An expression like:

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

Will produce a query like:

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

Because has() usesa correlated subquery, its performance is not nearly asgood when compared against large target tables as that ofusing a join.

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

  1. - <code>ilike</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.ilike)
  2. -

inherited from theilike()method ofColumnOperators

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

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

  1. lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

  1. a ILIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.ilike("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.like()

  1. - <code>in_</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.in_)
  2. -

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

  1. - <code>is_</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.is_)
  2. -

inherited from theis_()method ofColumnOperators

Implement the IS operator.

Normally, IS is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.isnot()

  1. - <code>is_distinct_from</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.is_distinct_from)
  2. -

inherited from theis_distinct_from()method ofColumnOperators

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.

  1. - <code>isnot</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.isnot)
  2. -

inherited from theisnot()method ofColumnOperators

Implement the IS NOT operator.

Normally, IS NOT is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS NOT may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.is_()

  1. - <code>isnot_distinct_from</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.isnot_distinct_from)
  2. -

inherited from theisnot_distinct_from()method ofColumnOperators

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.

  1. - <code>like</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.like)
  2. -

inherited from thelike()method ofColumnOperators

Implement the like operator.

In a column context, produces the expression:

  1. a LIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.like("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.ilike()

  1. - <code>mapper</code>[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.mapper)
  2. -

The target Mapper referred to by thisRelationshipProperty.Comparator.

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

  1. - <code>match</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.match)
  2. -

inherited from thematch()method ofColumnOperators

Implements a database-specific ‘match’ operator.

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

  1. -

PostgreSQL - renders x @@ to_tsquery(y)

  1. -

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

  1. -

Oracle - renders CONTAINS(x, y)

  1. -

other backends may provide special implementations.

  1. -

Backends without any special implementation will emitthe operator as “MATCH”. This is compatible with SQLite, forexample.

  1. - <code>notilike</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.notilike)
  2. -

inherited from thenotilike()method ofColumnOperators

implement the NOT ILIKE operator.

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

See also

ColumnOperators.ilike()

  1. - <code>notin_</code>(_other_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.notin_)
  2. -

inherited from thenotin_()method ofColumnOperators

implement the NOT IN operator.

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

In the case that other is an empty sequence, the compilerproduces an “empty not in” expression. This defaults to theexpression “1 = 1” to produce true in all cases. Thecreate_engine.empty_in_strategy may be used toalter this behavior.

Changed in version 1.2: The ColumnOperators.in_() andColumnOperators.notin_() operatorsnow produce a “static” expression for an empty IN sequenceby default.

See also

ColumnOperators.in_()

  1. - <code>notlike</code>(_other_, _escape=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.notlike)
  2. -

inherited from thenotlike()method ofColumnOperators

implement the NOT LIKE operator.

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

See also

ColumnOperators.like()

  1. - <code>nullsfirst</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.nullsfirst)
  2. -

inherited from thenullsfirst()method ofColumnOperators

Produce a nullsfirst() clause against theparent object.

  1. - <code>nullslast</code>()[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.nullslast)
  2. -

inherited from thenullslast()method ofColumnOperators

Produce a nullslast() clause against theparent object.

  1. - <code>of_type</code>(_cls_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.of_type)
  2. -

Redefine this object in terms of a polymorphic subclass.

See PropComparator.of_type() for an example.

  1. - <code>op</code>(_opstring_, _precedence=0_, _is_comparison=False_, _return_type=None_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.op)
  2. -

inherited from theop()method ofOperators

produce a generic operator function.

e.g.:

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

produces:

  1. somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

  1. - Parameters
  2. -
  3. -

operator – a string which will be output as the infix operatorbetween this element and the expression passed to thegenerated function.

  1. -

precedence – precedence to apply to the operator, whenparenthesizing expressions. A lower number will cause the expressionto be parenthesized when applied against another operator withhigher precedence. The default value of 0 is lower than alloperators except for the comma (,) and AS operators.A value of 100 will be higher or equal to all operators, and -100will be lower than or equal to all operators.

  1. -

is_comparison

if True, the operator will be considered as a“comparison” operator, that is which evaluates to a booleantrue/false value, like ==, >, etc. This flag should be setso that ORM relationships can establish that the operator is acomparison operator when used in a custom join condition.

New in version 0.9.2: - added theOperators.op.is_comparison flag.

  1. -

return_type

a TypeEngine class or object that willforce the return type of an expression produced by this operatorto be of that type. By default, operators that specifyOperators.op.is_comparison will resolve toBoolean, and those that do not will be of the sametype as the left-hand operand.

New in version 1.2.0b3: - added theOperators.op.return_type argument.

See also

Redefining and Creating New Operators

Using custom operators in join conditions

  1. - <code>operate</code>(_op_, _*other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.operate)
  2. -

inherited from theoperate()method ofOperators

Operate on an argument.

This is the lowest level of operation, raisesNotImplementedError by default.

Overriding this on a subclass can allow commonbehavior to be applied to all operations.For example, overriding ColumnOperatorsto apply func.lower() to the left and rightside:

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

op – Operator callable.

  1. -

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

  1. -

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

  1. - <code>reverse_operate</code>(_op_, _other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.reverse_operate)
  2. -

inherited from thereverse_operate()method ofOperators

Reverse operate on an argument.

Usage is the same as operate().

  1. - <code>startswith</code>(_other_, _**kwargs_)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.Comparator.startswith)
  2. -

inherited from thestartswith()method ofColumnOperators

Implement the startswith operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.startswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.startswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.startswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.startswith.autoescape:

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

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

See also

ColumnOperators.endswith()

ColumnOperators.contains()

ColumnOperators.like()

  • eq()

inherited from the eq() method of object

Return self==value.

  • 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, localremote_pairs=None, query_class=None, info=None, omit_join=None)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.properties.RelationshipProperty.init__)
  • Construct a new RelationshipProperty object.

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

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.orm.descriptorprops.SynonymProperty(_name, map_column=None, descriptor=None, comparator_factory=None, doc=None, info=None)
  • Bases: sqlalchemy.orm.descriptor_props.DescriptorProperty

    • eq()

inherited from the eq() method of object

Return self==value.

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

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

Base class for descriptor objects that interceptattribute events on behalf of a MapperPropertyobject. The actual MapperProperty is accessiblevia the QueryableAttribute.propertyattribute.

See also

InstrumentedAttribute

MapperProperty

Mapper.all_orm_descriptors

Mapper.attrs

  • eq(other)

inherited from theeq()method ofColumnOperators

Implement the == operator.

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

  • le(other)

inherited from thele()method ofColumnOperators

Implement the <= operator.

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

  • lt(other)

inherited from thelt()method ofColumnOperators

Implement the < operator.

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

  • ne(other)

inherited from thene()method ofColumnOperators

Implement the != operator.

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

inherited from theall_()method ofColumnOperators

Produce a all_() clause against theparent object.

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

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

See also

all_() - standalone version

any_() - ANY operator

New in version 1.1.

  • any(criterion=None, **kwargs)

inherited from theany()method ofPropComparator

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

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

  1. - Parameters
  2. -
  3. -

criterion – an optional ClauseElement formulated against themember class’ table or attributes.

  1. -

**kwargs – key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values.

inherited from theany_()method ofColumnOperators

Produce a any_() clause against theparent object.

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

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

See also

any_() - standalone version

all_() - ALL operator

New in version 1.1.

  • asc()

inherited from theasc()method ofColumnOperators

Produce a asc() clause against theparent object.

  • between(cleft, cright, symmetric=False)

inherited from thebetween()method ofColumnOperators

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

  • boolop(_opstring, precedence=0)

inherited from thebool_op()method ofOperators

Return a custom boolean operator.

This method is shorthand for callingOperators.op() and passing theOperators.op.is_comparisonflag with True.

New in version 1.2.0b3.

See also

Operators.op()

  • collate(collation)

inherited from thecollate()method ofColumnOperators

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

See also

collate()

  • concat(other)

inherited from theconcat()method ofColumnOperators

Implement the ‘concat’ operator.

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

  • contains(other, **kwargs)

inherited from thecontains()method ofColumnOperators

Implement the ‘contains’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.contains.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.contains.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.contains.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.contains.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.endswith()

ColumnOperators.like()

  • desc()

inherited from thedesc()method ofColumnOperators

Produce a desc() clause against theparent object.

  • distinct()

inherited from thedistinct()method ofColumnOperators

Produce a distinct() clause against theparent object.

  • endswith(other, **kwargs)

inherited from theendswith()method ofColumnOperators

Implement the ‘endswith’ operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.endswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.endswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.endswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.endswith.autoescape:

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

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

See also

ColumnOperators.startswith()

ColumnOperators.contains()

ColumnOperators.like()

  • extensiontype = symbol('NOTEXTENSION')
  • has(criterion=None, **kwargs)

inherited from thehas()method ofPropComparator

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

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

  1. - Parameters
  2. -
  3. -

criterion – an optional ClauseElement formulated against themember class’ table or attributes.

  1. -

**kwargs – key/value pairs corresponding to member classattribute names which will be compared via equality to thecorresponding values.

  • ilike(other, escape=None)

inherited from theilike()method ofColumnOperators

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

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

  1. lower(a) LIKE lower(other)

Or on backends that support the ILIKE operator:

  1. a ILIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.ilike("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.like()

  • in(_other)

inherited from thein_()method ofColumnOperators

Implement the in operator.

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

The given parameter other may be:

  1. -

A list of literal values, e.g.:

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

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

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

A list of tuples may be provided if the comparison is against atuple_() containing multiple expressions:

  1. from sqlalchemy import tuple_
  2. stmt.where(tuple_(col1, col2).in_([(1, 10), (2, 20), (3, 30)]))
  1. -

An empty list, e.g.:

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

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

  1. WHERE 1 != 1

This “false” expression has historically had different behaviorsin older SQLAlchemy versions, seecreate_engine.empty_in_strategy for behavioral options.

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

  1. -

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

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

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

  1. WHERE COL IN ([EXPANDING_value])

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

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

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

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

New in version 1.2: added “expanding” bound parameters

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

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

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

  1. -

a select() construct, which is usually a correlatedscalar select:

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

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

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

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

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

The behavior here is as follows:

  1. -

If the attribute is a column-mapped property, i.e.ColumnProperty, which is mapped directlyto a schema-level Column object, this attributewill return the SchemaItem.info dictionary associatedwith the core-level Column object.

  1. -

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

  1. -

If the attribute refers to any other kind ofMapperProperty, including RelationshipProperty,the attribute will refer to the MapperProperty.infodictionary associated with that MapperProperty.

  1. -

To access the MapperProperty.info dictionary of theMapperProperty unconditionally, including for aColumnProperty that’s associated directly with aschema.Column, the attribute can be referred to usingQueryableAttribute.property attribute, asMyClass.someattribute.property.info.

See also

SchemaItem.info

MapperProperty.info

  • is(_other)

inherited from theis_()method ofColumnOperators

Implement the IS operator.

Normally, IS is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.isnot()

  • isdistinct_from(_other)

inherited from theis_distinct_from()method ofColumnOperators

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)

inherited from theisnot()method ofColumnOperators

Implement the IS NOT operator.

Normally, IS NOT is generated automatically when comparing to avalue of None, which resolves to NULL. However, explicitusage of IS NOT may be desirable if comparing to boolean valueson certain platforms.

See also

ColumnOperators.is_()

  • isnotdistinct_from(_other)

inherited from theisnot_distinct_from()method ofColumnOperators

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)

inherited from thelike()method ofColumnOperators

Implement the like operator.

In a column context, produces the expression:

  1. a LIKE other

E.g.:

  1. stmt = select([sometable]).\
  2. where(sometable.c.column.like("%foobar%"))
  1. - Parameters
  2. -
  3. -

other – expression to be compared

  1. -

escape

optional escape character, renders the ESCAPEkeyword, e.g.:

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

See also

ColumnOperators.ilike()

  • match(other, **kwargs)

inherited from thematch()method ofColumnOperators

Implements a database-specific ‘match’ operator.

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

  1. -

PostgreSQL - renders x @@ to_tsquery(y)

  1. -

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

  1. -

Oracle - renders CONTAINS(x, y)

  1. -

other backends may provide special implementations.

  1. -

Backends without any special implementation will emitthe operator as “MATCH”. This is compatible with SQLite, forexample.

  • notilike(other, escape=None)

inherited from thenotilike()method ofColumnOperators

implement the NOT ILIKE operator.

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

See also

ColumnOperators.ilike()

  • notin(_other)

inherited from thenotin_()method ofColumnOperators

implement the NOT IN operator.

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

In the case that other is an empty sequence, the compilerproduces an “empty not in” expression. This defaults to theexpression “1 = 1” to produce true in all cases. Thecreate_engine.empty_in_strategy may be used toalter this behavior.

Changed in version 1.2: The ColumnOperators.in_() andColumnOperators.notin_() operatorsnow produce a “static” expression for an empty IN sequenceby default.

See also

ColumnOperators.in_()

  • notlike(other, escape=None)

inherited from thenotlike()method ofColumnOperators

implement the NOT LIKE operator.

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

See also

ColumnOperators.like()

  • nullsfirst()

inherited from thenullsfirst()method ofColumnOperators

Produce a nullsfirst() clause against theparent object.

  • nullslast()

inherited from thenullslast()method ofColumnOperators

Produce a nullslast() clause against theparent object.

  • oftype(_cls)
  • Redefine this object in terms of a polymorphic subclass.

Returns a new PropComparator from which further criterion can beevaluated.

e.g.:

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

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

See also

Referring to specific subtypes on relationships

  • op(opstring, precedence=0, is_comparison=False, return_type=None)

inherited from theop()method ofOperators

produce a generic operator function.

e.g.:

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

produces:

  1. somecolumn * 5

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

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

is a bitwise AND of the value in somecolumn.

  1. - Parameters
  2. -
  3. -

operator – a string which will be output as the infix operatorbetween this element and the expression passed to thegenerated function.

  1. -

precedence – precedence to apply to the operator, whenparenthesizing expressions. A lower number will cause the expressionto be parenthesized when applied against another operator withhigher precedence. The default value of 0 is lower than alloperators except for the comma (,) and AS operators.A value of 100 will be higher or equal to all operators, and -100will be lower than or equal to all operators.

  1. -

is_comparison

if True, the operator will be considered as a“comparison” operator, that is which evaluates to a booleantrue/false value, like ==, >, etc. This flag should be setso that ORM relationships can establish that the operator is acomparison operator when used in a custom join condition.

New in version 0.9.2: - added theOperators.op.is_comparison flag.

  1. -

return_type

a TypeEngine class or object that willforce the return type of an expression produced by this operatorto be of that type. By default, operators that specifyOperators.op.is_comparison will resolve toBoolean, and those that do not will be of the sametype as the left-hand operand.

New in version 1.2.0b3: - added theOperators.op.return_type argument.

See also

Redefining and Creating New Operators

Using custom operators in join conditions

  • operate(op, *other, **kwargs)
  • Operate on an argument.

This is the lowest level of operation, raisesNotImplementedError by default.

Overriding this on a subclass can allow commonbehavior to be applied to all operations.For example, overriding ColumnOperatorsto apply func.lower() to the left and rightside:

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

op – Operator callable.

  1. -

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

  1. -

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

  • parent
  • Return an inspection instance representing the parent.

This will be either an instance of Mapperor AliasedInsp, depending upon the natureof the parent entity which this attribute is associatedwith.

Return values here will commonly be instances ofColumnProperty or RelationshipProperty.

  • reverseoperate(_op, other, **kwargs)
  • Reverse operate on an argument.

Usage is the same as operate().

  • startswith(other, **kwargs)

inherited from thestartswith()method ofColumnOperators

Implement the startswith operator.

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

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

E.g.:

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

Since the operator uses LIKE, wildcard characters"%" and "_" that are present inside the expressionwill behave like wildcards as well. For literal stringvalues, the ColumnOperators.startswith.autoescape flagmay be set to True to apply escaping to occurrences of thesecharacters within the string value so that they match as themselvesand not as wildcard characters. Alternatively, theColumnOperators.startswith.escape parameter will establisha given character as an escape character which can be of use whenthe target expression is not a literal string.

  1. - Parameters
  2. -
  3. -

other – expression to be compared. This is usually a plainstring value, but can also be an arbitrary SQL expression. LIKEwildcard characters % and _ are not escaped by default unlessthe ColumnOperators.startswith.autoescape flag isset to True.

  1. -

autoescape

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

An expression such as:

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

Will render as:

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

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

New in version 1.2.

Changed in version 1.2.0: TheColumnOperators.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.

  1. -

escape

a character which when given will render with theESCAPE keyword to establish that character as the escapecharacter. This character can then be placed preceding occurrencesof % and _ to allow them to act as themselves and notwildcard characters.

An expression such as:

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

Will render as:

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

The parameter may also be combined withColumnOperators.startswith.autoescape:

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

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

See also

ColumnOperators.endswith()

ColumnOperators.contains()

ColumnOperators.like()

  • class sqlalchemy.orm.session.UOWTransaction(session)
    • filterstates_for_dep(_dep, states)
    • Filter the given list of InstanceStates to those relevant to thegiven DependencyProcessor.

    • finalize_flush_changes()

    • mark processed objects as clean / deleted after a successfulflush().

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

  • getattribute_history(_state, key, passive=symbol('PASSIVE_NO_INITIALIZE'))
  • facade to attributes.get_state_history(), includingcaching of results.

  • isdeleted(_state)

  • return true if the given state is marked as deletedwithin this uowtransaction.

  • removestate_actions(_state)

  • remove pending actions for a state from the uowtransaction.

  • wasalready_deleted(_state)

  • return true if the given state is expired and was deletedpreviously.