Functional constructs for ORM configuration.

See the SQLAlchemy object relational tutorial and mapper configurationdocumentation for an overview of how this module is used.

Relationships API

  • sqlalchemy.orm.relationship(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)
  • Provide a relationship between two mapped classes.

This corresponds to a parent-child or associative table relationship.The constructed class is an instance ofRelationshipProperty.

A typical relationship(), used in a classical mapping:

  1. mapper(Parent, properties={
  2. 'children': relationship(Child)
  3. })

Some arguments accepted by relationship() optionally accept acallable function, which when called produces the desired value.The callable is invoked by the parent Mapper at “mapperinitialization” time, which happens only when mappers are first used,and is assumed to be after all mappings have been constructed. Thiscan be used to resolve order-of-declaration and other dependencyissues, such as if Child is declared below Parent in the samefile:

  1. mapper(Parent, properties={
  2. "children":relationship(lambda: Child,
  3. order_by=lambda: Child.id)
  4. })

When using the Declarative extension, the Declarativeinitializer allows string arguments to be passed torelationship(). These string arguments are converted intocallables that evaluate the string as Python code, using theDeclarative class-registry as a namespace. This allows the lookup ofrelated classes to be automatic via their string name, and removes theneed for related classes to be imported into the local module spacebefore the dependent classes have been declared. It is still requiredthat the modules in which these related classes appear are importedanywhere in the application at some point before the related mappingsare actually used, else a lookup error will be raised when therelationship() attempts to resolve the string reference to therelated class. An example of a string- resolved class is asfollows:

  1. from sqlalchemy.ext.declarative import declarative_base
  2.  
  3. Base = declarative_base()
  4.  
  5. class Parent(Base):
  6. __tablename__ = 'parent'
  7. id = Column(Integer, primary_key=True)
  8. children = relationship("Child", order_by="Child.id")

See also

Relationship Configuration - Full introductory andreference documentation for relationship().

Building a Relationship - ORM tutorial introduction.

  • Parameters
    • argument

a mapped class, or actual Mapper instance, representingthe target of the relationship.

argument may also be passed as a callablefunction which is evaluated at mapper initialization time, and maybe passed as a Python-evaluable string when using Declarative.

See also

Configuring Relationships - further detailon relationship configuration when using Declarative.

  1. -

secondary

for a many-to-many relationship, specifies the intermediarytable, and is typically an instance of Table.In less common circumstances, the argument may also be specifiedas an Alias construct, or even a Join construct.

secondary mayalso be passed as a callable function which is evaluated atmapper initialization time. When using Declarative, it may alsobe a string argument noting the name of a Table that ispresent in the MetaData collection associated with theparent-mapped Table.

The secondary keyword argument istypically applied in the case where the intermediary Tableis not otherwise expressed in any direct class mapping. If the“secondary” table is also explicitly mapped elsewhere (e.g. as inAssociation Object), one should consider applying theviewonly flag so that thisrelationship() is not used for persistence operations whichmay conflict with those of the association object pattern.

See also

Many To Many - Reference example of “manyto many”.

Building a Many To Many Relationship - ORM tutorial introduction tomany-to-many relationships.

Self-Referential Many-to-Many Relationship - Specifics on usingmany-to-many in a self-referential case.

Configuring Many-to-Many Relationships - Additional options when usingDeclarative.

Association Object - an alternative tosecondary when composing associationtable relationships, allowing additional attributes to bespecified on the association table.

Composite “Secondary” Joins - a lesser-used pattern whichin some cases can enable complex relationship() SQLconditions to be used.

New in version 0.9.2: secondary worksmore effectively when referring to a Join instance.

  1. -

active_history=False – When True, indicates that the “previous” value for amany-to-one reference should be loaded when replaced, ifnot already loaded. Normally, history tracking logic forsimple many-to-ones only needs to be aware of the “new”value in order to perform a flush. This flag is availablefor applications that make use ofattributes.get_history() which also need to knowthe “previous” value of the attribute.

  1. -

backref

indicates the string name of a property to be placed on the relatedmapper’s class that will handle this relationship in the otherdirection. The other property will be created automaticallywhen the mappers are configured. Can also be passed as abackref() object to control the configuration of thenew relationship.

See also

Linking Relationships with Backref - Introductory documentation andexamples.

back_populates - alternative formof backref specification.

backref() - allows control over relationship()configuration when using backref.

  1. -

back_populates

Takes a string name and has the same meaning asbackref, except the complementingproperty is not created automatically, and instead must beconfigured explicitly on the other mapper. The complementingproperty should also indicateback_populates to this relationship toensure proper functioning.

See also

Linking Relationships with Backref - Introductory documentation andexamples.

backref - alternative formof backref specification.

  1. -

bake_queries=True

Use the BakedQuery cache to cache the construction of SQLused in lazy loads. True by default. Set to False if thejoin condition of the relationship has unusual features thatmight not respond well to statement caching.

Changed in version 1.2: “Baked” loading is the default implementation for the “select”,a.k.a. “lazy” loading strategy for relationships.

New in version 1.0.0.

See also

Baked Queries

  1. -

cascade

a comma-separated list of cascade rules which determines howSession operations should be “cascaded” from parent to child.This defaults to False, which means the default cascadeshould be used - this default cascade is "save-update, merge".

The available cascades are save-update, merge,expunge, delete, delete-orphan, and refresh-expire.An additional option, all indicates shorthand for"save-update, merge, refresh-expire,expunge, delete", and is often used as in "all, delete-orphan"to indicate that related objects should follow along with theparent object in all cases, and be deleted when de-associated.

See also

Cascades - Full detail on each of the availablecascade options.

Configuring delete/delete-orphan Cascade - Tutorial example describinga delete cascade.

  1. -

cascade_backrefs=True

a boolean value indicating if the save-update cascade shouldoperate along an assignment event intercepted by a backref.When set to False, the attribute managed by this relationshipwill not cascade an incoming transient object into the session of apersistent parent, if the event is received via backref.

See also

Controlling Cascade on Backrefs - Full discussion and examples on howthe cascade_backrefs option is used.

  1. -

collection_class

a class or callable that returns a new list-holding object. willbe used in place of a plain list for storing elements.

See also

Customizing Collection Access - Introductory documentation andexamples.

  1. -

comparator_factory

a class which extends RelationshipProperty.Comparatorwhich provides custom SQL clause generation for comparisonoperations.

See also

PropComparator - some detail on redefining comparatorsat this level.

Operator Customization - Brief intro to this feature.

  1. -

distinct_target_key=None

Indicate if a “subquery” eager load should apply the DISTINCTkeyword to the innermost SELECT statement. When left as None,the DISTINCT keyword will be applied in those cases when the targetcolumns do not comprise the full primary key of the target table.When set to True, the DISTINCT keyword is applied to theinnermost SELECT unconditionally.

It may be desirable to set this flag to False when the DISTINCT isreducing performance of the innermost subquery beyond that of whatduplicate innermost rows may be causing.

Changed in version 0.9.0: -distinct_target_key now defaults toNone, so that the feature enables itself automatically forthose cases where the innermost query targets a non-uniquekey.

See also

Relationship Loading Techniques - includes an introduction to subqueryeager loading.

  1. -

doc – docstring which will be applied to the resulting descriptor.

  1. -

extension

an AttributeExtension instance, or list of extensions,which will be prepended to the list of attribute listeners forthe resulting descriptor placed on the class.

Deprecated since version 0.7: AttributeExtension is deprecated in favor of the AttributeEvents listener interface. The relationship.extension parameter will be removed in a future release.

  1. -

foreign_keys

a list of columns which are to be used as “foreign key”columns, or columns which refer to the value in a remotecolumn, within the context of this relationship()object’s primaryjoin condition.That is, if the primaryjoincondition of this relationship() is a.id ==b.a_id, and the values in b.a_id are required to bepresent in a.id, then the “foreign key” column of thisrelationship() is b.a_id.

In normal cases, the foreign_keysparameter is not required.relationship() willautomatically determine which columns in theprimaryjoin condition are to beconsidered “foreign key” columns based on thoseColumn objects that specify ForeignKey,or are otherwise listed as referencing columns in aForeignKeyConstraint construct.foreign_keys is only needed when:

  1. There is more than one way to construct a join from the localtable to the remote table, as there are multiple foreign keyreferences present. Setting foreign_keys will limit therelationship() to consider just those columns specifiedhere as “foreign”.

  2. The Table being mapped does not actually haveForeignKey or ForeignKeyConstraintconstructs present, often because the tablewas reflected from a database that does not support foreign keyreflection (MySQL MyISAM).

  3. The primaryjoin argument is used toconstruct a non-standard join condition, which makes use ofcolumns or expressions that do not normally refer to their“parent” column, such as a join condition expressed by acomplex comparison using a SQL function.

The relationship() construct will raise informativeerror messages that suggest the use of theforeign_keys parameter whenpresented with an ambiguous condition. In typical cases,if relationship() doesn’t raise any exceptions, theforeign_keys parameter is usuallynot needed.

foreign_keys may also be passed as acallable function which is evaluated at mapper initialization time,and may be passed as a Python-evaluable string when usingDeclarative.

See also

Handling Multiple Join Paths

Creating Custom Foreign Conditions

foreign() - allows direct annotation of the “foreign”columns within a primaryjoin condition.

  1. -

info – Optional data dictionary which will be populated into theMapperProperty.info attribute of this object.

  1. -

innerjoin=False

when True, joined eager loads will use an inner join to joinagainst related tables instead of an outer join. The purposeof this option is generally one of performance, as inner joinsgenerally perform better than outer joins.

This flag can be set to True when the relationship references anobject via many-to-one using local foreign keys that are notnullable, or when the reference is one-to-one or a collection thatis guaranteed to have one or at least one entry.

The option supports the same “nested” and “unnested” options asthat of joinedload.innerjoin. See that flagfor details on nested / unnested behaviors.

See also

joinedload.innerjoin - the option as specified byloader option, including detail on nesting behavior.

What Kind of Loading to Use ? - Discussion of some details ofvarious loader options.

  1. -

join_depth

when non-None, an integer value indicating how many levelsdeep “eager” loaders should join on a self-referring or cyclicalrelationship. The number counts how many times the same Mappershall be present in the loading condition along a particular joinbranch. When left at its default of None, eager loaderswill stop chaining when they encounter a the same target mapperwhich is already higher up in the chain. This option appliesboth to joined- and subquery- eager loaders.

See also

Configuring Self-Referential Eager Loading - Introductory documentationand examples.

  1. -

lazy='select'

specifieshow the related items should be loaded. Default value isselect. Values include:

  1. -

select - items should be loaded lazily when the property isfirst accessed, using a separate SELECT statement, or identity mapfetch for simple many-to-one references.

  1. -

immediate - items should be loaded as the parents are loaded,using a separate SELECT statement, or identity map fetch forsimple many-to-one references.

  1. -

joined - items should be loaded “eagerly” in the same query asthat of the parent, using a JOIN or LEFT OUTER JOIN. Whetherthe join is “outer” or not is determined by theinnerjoin parameter.

  1. -

subquery - items should be loaded “eagerly” as the parents areloaded, using one additional SQL statement, which issues a JOIN toa subquery of the original statement, for each collectionrequested.

  1. -

selectin - items should be loaded “eagerly” as the parentsare loaded, using one or more additional SQL statements, whichissues a JOIN to the immediate parent object, specifying primarykey identifiers using an IN clause.

New in version 1.2.

  1. -

noload - no loading should occur at any time. This is tosupport “write-only” attributes, or attributes which arepopulated in some manner specific to the application.

  1. -

raise - lazy loading is disallowed; accessingthe attribute, if its value were not already loaded via eagerloading, will raise an InvalidRequestError.This strategy can be used when objects are to be detached fromtheir attached Session after they are loaded.

New in version 1.1.

  1. -

raise_on_sql - lazy loading that emits SQL is disallowed;accessing the attribute, if its value were not already loaded viaeager loading, will raise anInvalidRequestError, if the lazy loadneeds to emit SQL. If the lazy load can pull the related valuefrom the identity map or determine that it should be None, thevalue is loaded. This strategy can be used when objects willremain associated with the attached Session, howeveradditional SELECT statements should be blocked.

New in version 1.1.

  1. -

dynamic - the attribute will return a pre-configuredQuery object for all readoperations, onto which further filtering operations can beapplied before iterating the results. Seethe section Dynamic Relationship Loaders for more details.

  1. -

True - a synonym for ‘select’

  1. -

False - a synonym for ‘joined’

  1. -

None - a synonym for ‘noload’

See also

Relationship Loading Techniques - Full documentation onrelationship loader configuration.

Dynamic Relationship Loaders - detail on the dynamic option.

Setting Noload, RaiseLoad - notes on “noload” and “raise”

  1. -

load_on_pending=False

Indicates loading behavior for transient or pending parent objects.

When set to True, causes the lazy-loader toissue a query for a parent object that is not persistent, meaning ithas never been flushed. This may take effect for a pending objectwhen autoflush is disabled, or for a transient object that has been“attached” to a Session but is not part of its pendingcollection.

The load_on_pending flag does not improvebehavior when the ORM is used normally - object references should beconstructed at the object level, not at the foreign key level, sothat they are present in an ordinary way before a flush proceeds.This flag is not not intended for general use.

See also

Session.enable_relationship_loading() - this methodestablishes “load on pending” behavior for the whole object, andalso allows loading on objects that remain transient ordetached.

  1. -

order_by

indicates the ordering that should be applied when loading theseitems. order_by is expected to refer toone of the Column objects to which the target class ismapped, or the attribute itself bound to the target class whichrefers to the column.

order_by may also be passed as a callablefunction which is evaluated at mapper initialization time, and maybe passed as a Python-evaluable string when using Declarative.

  1. -

passive_deletes=False

Indicates loading behavior during delete operations.

A value of True indicates that unloaded child items should notbe loaded during a delete operation on the parent. Normally,when a parent item is deleted, all child items are loaded sothat they can either be marked as deleted, or have theirforeign key to the parent set to NULL. Marking this flag asTrue usually implies an ON DELETE rule is inplace which will handle updating/deleting child rows on thedatabase side.

Additionally, setting the flag to the string value ‘all’ willdisable the “nulling out” of the child foreign keys, when the parentobject is deleted and there is no delete or delete-orphan cascadeenabled. This is typically used when a triggering or error raisescenario is in place on the database side. Note that the foreignkey attributes on in-session child objects will not be changed aftera flush occurs so this is a very special use-case setting.Additionally, the “nulling out” will still occur if the childobject is de-associated with the parent.

See also

Using Passive Deletes - Introductory documentationand examples.

  1. -

passive_updates=True

Indicates the persistence behavior to take when a referencedprimary key value changes in place, indicating that the referencingforeign key columns will also need their value changed.

When True, it is assumed that ON UPDATE CASCADE is configured onthe foreign key in the database, and that the database willhandle propagation of an UPDATE from a source column todependent rows. When False, the SQLAlchemy relationship()construct will attempt to emit its own UPDATE statements tomodify related targets. However note that SQLAlchemy cannotemit an UPDATE for more than one level of cascade. Also,setting this flag to False is not compatible in the case wherethe database is in fact enforcing referential integrity, unlessthose constraints are explicitly “deferred”, if the target backendsupports it.

It is highly advised that an application which is employingmutable primary keys keeps passive_updates set to True,and instead uses the referential integrity features of the databaseitself in order to handle the change efficiently and fully.

See also

Mutable Primary Keys / Update Cascades - Introductory documentation andexamples.

mapper.passive_updates - a similar flag whichtakes effect for joined-table inheritance mappings.

  1. -

post_update

this indicates that the relationship should be handled by asecond UPDATE statement after an INSERT or before aDELETE. Currently, it also will issue an UPDATE after theinstance was UPDATEd as well, although this technically shouldbe improved. This flag is used to handle saving bi-directionaldependencies between two individual rows (i.e. each rowreferences the other), where it would otherwise be impossible toINSERT or DELETE both rows fully since one row exists before theother. Use this flag when a particular mapping arrangement willincur two rows that are dependent on each other, such as a tablethat has a one-to-many relationship to a set of child rows, andalso has a column that references a single child row within thatlist (i.e. both tables contain a foreign key to each other). Ifa flush operation returns an error that a “cyclicaldependency” was detected, this is a cue that you might want touse post_update to “break” the cycle.

See also

Rows that point to themselves / Mutually Dependent Rows - Introductory documentation and examples.

  1. -

primaryjoin

a SQL expression that will be used as the primaryjoin of the child object against the parent object, or in amany-to-many relationship the join of the parent object to theassociation table. By default, this value is computed based on theforeign key relationships of the parent and child tables (orassociation table).

primaryjoin may also be passed as acallable function which is evaluated at mapper initialization time,and may be passed as a Python-evaluable string when usingDeclarative.

See also

Specifying Alternate Join Conditions

  1. -

remote_side

used for self-referential relationships, indicates the column orlist of columns that form the “remote side” of the relationship.

relationship.remote_side may also be passed as acallable function which is evaluated at mapper initialization time,and may be passed as a Python-evaluable string when usingDeclarative.

See also

Adjacency List Relationships - in-depth explanation of howremote_sideis used to configure self-referential relationships.

remote() - an annotation function that accomplishes thesame purpose as remote_side, typicallywhen a custom primaryjoin conditionis used.

  1. -

query_class

a Query subclass that will be used as the base of the“appender query” returned by a “dynamic” relationship, thatis, a relationship that specifies lazy="dynamic" or wasotherwise constructed using the orm.dynamic_loader()function.

See also

Dynamic Relationship Loaders - Introduction to “dynamic”relationship loaders.

  1. -

secondaryjoin

a SQL expression that will be used as the join ofan association table to the child object. By default, this value iscomputed based on the foreign key relationships of the associationand child tables.

secondaryjoin may also be passed as acallable function which is evaluated at mapper initialization time,and may be passed as a Python-evaluable string when usingDeclarative.

See also

Specifying Alternate Join Conditions

  1. -

single_parent

when True, installs a validator which will prevent objectsfrom being associated with more than one parent at a time.This is used for many-to-one or many-to-many relationships thatshould be treated either as one-to-one or one-to-many. Its usageis optional, except for relationship() constructs whichare many-to-one or many-to-many and alsospecify the delete-orphan cascade option. Therelationship() construct itself will raise an errorinstructing when this option is required.

See also

Cascades - includes detail on when thesingle_parent flag may be appropriate.

  1. -

uselist

a boolean that indicates if this property should be loaded as alist or a scalar. In most cases, this value is determinedautomatically by relationship() at mapper configurationtime, based on the type and directionof the relationship - one to many forms a list, many to oneforms a scalar, many to many is a list. If a scalar is desiredwhere normally a list would be present, such as a bi-directionalone-to-one relationship, set uselist toFalse.

The uselist flag is also available on anexisting relationship() construct as a read-only attribute,which can be used to determine if this relationship() dealswith collections or scalar attributes:

  1. >>> User.addresses.property.uselist
  2. True

See also

One To One - Introduction to the “one toone” relationship pattern, which is typically when theuselist flag is needed.

  1. -

viewonly=False – when set to True, the relationship is used only for loading objects,and not for any persistence operation. A relationship()which specifies viewonly can workwith a wider range of SQL operations within theprimaryjoin condition, includingoperations that feature the use of a variety of comparison operatorsas well as SQL functions such as cast(). Theviewonly flag is also of general use whendefining any kind of relationship() that doesn’t representthe full set of related objects, to prevent modifications of thecollection from resulting in persistence operations.

  1. -

omit_join

Allows manual control over the “selectin” automatic joinoptimization. Set to False to disable the “omit join” featureadded in SQLAlchemy 1.3.

New in version 1.3.

  • sqlalchemy.orm.backref(name, **kwargs)
  • Create a back reference with explicit keyword arguments, which are thesame arguments one can send to relationship().

Used with the backref keyword argument to relationship() inplace of a string argument, e.g.:

  1. 'items':relationship(
  2. SomeItem, backref=backref('parent', lazy='subquery'))

See also

Linking Relationships with Backref

  • sqlalchemy.orm.relation(*arg, **kw)
  • A synonym for relationship().

  • sqlalchemy.orm.dynamicloader(_argument, **kw)

  • Construct a dynamically-loading mapper property.

This is essentially the same asusing the lazy='dynamic' argument with relationship():

  1. dynamic_loader(SomeClass)
  2.  
  3. # is the same as
  4.  
  5. relationship(SomeClass, lazy="dynamic")

See the section Dynamic Relationship Loaders for more detailson dynamic loading.

  • sqlalchemy.orm.foreign(expr)
  • Annotate a portion of a primaryjoin expressionwith a ‘foreign’ annotation.

See the section Creating Custom Foreign Conditions for adescription of use.

See also

Creating Custom Foreign Conditions

remote()

  • sqlalchemy.orm.remote(expr)
  • Annotate a portion of a primaryjoin expressionwith a ‘remote’ annotation.

See the section Creating Custom Foreign Conditions for adescription of use.

See also

Creating Custom Foreign Conditions

foreign()