SQLAlchemy 0.6 Documentation

Release: 0.6.9 | Release Date: May 5, 2012
SQLAlchemy 0.6 Documentation » SQLAlchemy ORM » Relationship Configuration

Relationship Configuration

Relationship Configuration

This section describes the relationship() function and in depth discussion of its usage. The reference material here continues into the next section, Collection Configuration and Techniques, which has additional detail on configuration of collections via relationship().

Basic Relational Patterns

A quick walkthrough of the basic relational patterns. In this section we illustrate the classical mapping using mapper() in conjunction with relationship(). Then (by popular demand), we illustrate the declarative form using the declarative module.

Note that relationship() is historically known as relation() in older versions of SQLAlchemy.

One To Many

A one to many relationship places a foreign key in the child table referencing the parent. SQLAlchemy creates the relationship as a collection on the parent object containing instances of the child object.

parent_table = Table('parent', metadata,
    Column('id', Integer, primary_key=True))

child_table = Table('child', metadata,
    Column('id', Integer, primary_key=True),
    Column('parent_id', Integer, ForeignKey('parent.id'))
)

class Parent(object):
    pass

class Child(object):
    pass

mapper(Parent, parent_table, properties={
    'children': relationship(Child)
})

mapper(Child, child_table)

To establish a bi-directional relationship in one-to-many, where the “reverse” side is a many to one, specify the backref option:

mapper(Parent, parent_table, properties={
    'children': relationship(Child, backref='parent')
})

mapper(Child, child_table)

Child will get a parent attribute with many-to-one semantics.

Declarative:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    children = relationship("Child", backref="parent")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('parent.id'))

Many To One

Many to one places a foreign key in the parent table referencing the child. The mapping setup is identical to one-to-many, however SQLAlchemy creates the relationship as a scalar attribute on the parent object referencing a single instance of the child object.

parent_table = Table('parent', metadata,
    Column('id', Integer, primary_key=True),
    Column('child_id', Integer, ForeignKey('child.id')))

child_table = Table('child', metadata,
    Column('id', Integer, primary_key=True),
    )

class Parent(object):
    pass

class Child(object):
    pass

mapper(Parent, parent_table, properties={
    'child': relationship(Child)
})

mapper(Child, child_table)

Backref behavior is available here as well, where backref="parents" will place a one-to-many collection on the Child class:

mapper(Parent, parent_table, properties={
    'child': relationship(Child, backref="parents")
})

Declarative:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref="parents")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

One To One

One To One is essentially a bi-directional relationship with a scalar attribute on both sides. To achieve this, the uselist=False flag indicates the placement of a scalar attribute instead of a collection on the “many” side of the relationship. To convert one-to-many into one-to-one:

parent_table = Table('parent', metadata,
    Column('id', Integer, primary_key=True)
)

child_table = Table('child', metadata,
    Column('id', Integer, primary_key=True),
    Column('parent_id', Integer, ForeignKey('parent.id'))
)

mapper(Parent, parent_table, properties={
    'child': relationship(Child, uselist=False, backref='parent')
})

mapper(Child, child_table)

Or to turn a one-to-many backref into one-to-one, use the backref() function to provide arguments for the reverse side:

from sqlalchemy.orm import backref

parent_table = Table('parent', metadata,
    Column('id', Integer, primary_key=True),
    Column('child_id', Integer, ForeignKey('child.id'))
)

child_table = Table('child', metadata,
    Column('id', Integer, primary_key=True)
)

mapper(Parent, parent_table, properties={
    'child': relationship(Child, backref=backref('parent', uselist=False))
})

mapper(Child, child_table)

The second example above as declarative:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref=backref("parent", uselist=False))

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

Many To Many

Many to Many adds an association table between two classes. The association table is indicated by the secondary argument to relationship().

left_table = Table('left', metadata,
    Column('id', Integer, primary_key=True)
)

right_table = Table('right', metadata,
    Column('id', Integer, primary_key=True)
)

association_table = Table('association', metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

mapper(Parent, left_table, properties={
    'children': relationship(Child, secondary=association_table)
})

mapper(Child, right_table)

For a bi-directional relationship, both sides of the relationship contain a collection. The backref keyword will automatically use the same secondary argument for the reverse relationship:

mapper(Parent, left_table, properties={
    'children': relationship(Child, secondary=association_table,
                                    backref='parents')
})

With declarative, we still use the Table for the secondary argument. A class is not mapped to this table, so it remains in its plain schematic form:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                    secondary=association_table,
                    backref="parents")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

Association Object

The association object pattern is a variant on many-to-many: it specifically is used when your association table contains additional columns beyond those which are foreign keys to the left and right tables. Instead of using the secondary argument, you map a new class directly to the association table. The left side of the relationship references the association object via one-to-many, and the association class references the right side via many-to-one.

left_table = Table('left', metadata,
    Column('id', Integer, primary_key=True)
)

right_table = Table('right', metadata,
    Column('id', Integer, primary_key=True)
)

association_table = Table('association', metadata,
    Column('left_id', Integer, ForeignKey('left.id'), primary_key=True),
    Column('right_id', Integer, ForeignKey('right.id'), primary_key=True),
    Column('data', String(50))
)

mapper(Parent, left_table, properties={
    'children':relationship(Association)
})

mapper(Association, association_table, properties={
    'child':relationship(Child)
})

mapper(Child, right_table)

The bi-directional version adds backrefs to both relationships:

mapper(Parent, left_table, properties={
    'children':relationship(Association, backref="parent")
})

mapper(Association, association_table, properties={
    'child':relationship(Child, backref="parent_assocs")
})

mapper(Child, right_table)

Declarative:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    child = relationship("Child", backref="parent_assocs")

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship(Association, backref="parent")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

Working with the association pattern in its direct form requires that child objects are associated with an association instance before being appended to the parent; similarly, access from parent to child goes through the association object:

# create parent, append a child via association
p = Parent()
a = Association()
a.child = Child()
p.children.append(a)

# iterate through child objects via association, including association
# attributes
for assoc in p.children:
    print assoc.data
    print assoc.child

To enhance the association object pattern such that direct access to the Association object is optional, SQLAlchemy provides the Association Proxy extension. This extension allows the configuration of attributes which will access two “hops” with a single access, one “hop” to the associated object, and a second to a target attribute.

Note

When using the association object pattern, it is advisable that the association-mapped table not be used as the secondary argument on a relationship() elsewhere, unless that relationship() contains the option viewonly=True. SQLAlchemy otherwise may attempt to emit redundant INSERT and DELETE statements on the same table, if similar state is detected on the related attribute as well as the associated object.

Adjacency List Relationships

The adjacency list pattern is a common relational pattern whereby a table contains a foreign key reference to itself. This is the most common and simple way to represent hierarchical data in flat tables. The other way is the “nested sets” model, sometimes called “modified preorder”. Despite what many online articles say about modified preorder, the adjacency list model is probably the most appropriate pattern for the large majority of hierarchical storage needs, for reasons of concurrency, reduced complexity, and that modified preorder has little advantage over an application which can fully load subtrees into the application space.

SQLAlchemy commonly refers to an adjacency list relationship as a self-referential mapper. In this example, we’ll work with a single table called nodes to represent a tree structure:

nodes = Table('nodes', metadata,
    Column('id', Integer, primary_key=True),
    Column('parent_id', Integer, ForeignKey('nodes.id')),
    Column('data', String(50)),
    )

A graph such as the following:

root --+---> child1
       +---> child2 --+--> subchild1
       |              +--> subchild2
       +---> child3

Would be represented with data such as:

id       parent_id     data
---      -------       ----
1        NULL          root
2        1             child1
3        1             child2
4        3             subchild1
5        3             subchild2
6        1             child3

SQLAlchemy’s mapper() configuration for a self-referential one-to-many relationship is exactly like a “normal” one-to-many relationship. When SQLAlchemy encounters the foreign key relationship from nodes to nodes, it assumes one-to-many unless told otherwise:

# entity class
class Node(object):
    pass

mapper(Node, nodes, properties={
    'children': relationship(Node)
})

To create a many-to-one relationship from child to parent, an extra indicator of the “remote side” is added, which contains the Column object or objects indicating the remote side of the relationship:

mapper(Node, nodes, properties={
    'parent': relationship(Node, remote_side=[nodes.c.id])
})

And the bi-directional version combines both:

mapper(Node, nodes, properties={
    'children': relationship(Node,
                        backref=backref('parent', remote_side=[nodes.c.id])
                    )
})

For comparison, the declarative version typically uses the inline id Column attribute to declare remote_side (note the list form is optional when the collection is only one column):

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class Node(Base):
    __tablename__ = 'nodes'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey('nodes.id'))
    data = Column(String(50))
    children = relationship("Node",
                    backref=backref('parent', remote_side=id)
                )

There are several examples included with SQLAlchemy illustrating self-referential strategies; these include Adjacency List and XML Persistence.

Self-Referential Query Strategies

Querying self-referential structures is done in the same way as any other query in SQLAlchemy, such as below, we query for any node whose data attribute stores the value child2:

# get all nodes named 'child2'
session.query(Node).filter(Node.data=='child2')

On the subject of joins, i.e. those described in datamapping_joins, self-referential structures require the usage of aliases so that the same table can be referenced multiple times within the FROM clause of the query. Aliasing can be done either manually using the nodes Table object as a source of aliases:

# get all nodes named 'subchild1' with a parent named 'child2'
nodealias = nodes.alias()
sqlsession.query(Node).filter(Node.data=='subchild1').\
    filter(and_(Node.parent_id==nodealias.c.id, nodealias.c.data=='child2')).all()

or automatically, using join() with aliased=True:

# get all nodes named 'subchild1' with a parent named 'child2'
sqlsession.query(Node).filter(Node.data=='subchild1').\
    join('parent', aliased=True).filter(Node.data=='child2').all()

To add criterion to multiple points along a longer join, use from_joinpoint=True:

# get all nodes named 'subchild1' with a parent named 'child2' and a grandparent 'root'
sqlsession.query(Node).filter(Node.data=='subchild1').\
    join('parent', aliased=True).filter(Node.data=='child2').\
    join('parent', aliased=True, from_joinpoint=True).filter(Node.data=='root').all()

Configuring Eager Loading

Eager loading of relationships occurs using joins or outerjoins from parent to child table during a normal query operation, such that the parent and its child collection can be populated from a single SQL statement, or a second statement for all collections at once. SQLAlchemy’s joined and subquery eager loading uses aliased tables in all cases when joining to related items, so it is compatible with self-referential joining. However, to use eager loading with a self-referential relationship, SQLAlchemy needs to be told how many levels deep it should join; otherwise the eager load will not take place. This depth setting is configured via join_depth:

mapper(Node, nodes, properties={
    'children': relationship(Node, lazy='joined', join_depth=2)
})

sqlsession.query(Node).all()

Specifying Alternate Join Conditions to relationship()

The relationship() function uses the foreign key relationship between the parent and child tables to formulate the primary join condition between parent and child; in the case of a many-to-many relationship it also formulates the secondary join condition:

one to many/many to one:
------------------------

parent_table -->  parent_table.c.id == child_table.c.parent_id -->  child_table
                               primaryjoin

many to many:
-------------

parent_table -->  parent_table.c.id == secondary_table.c.parent_id -->
                               primaryjoin

                  secondary_table.c.child_id == child_table.c.id --> child_table
                              secondaryjoin

If you are working with a Table which has no ForeignKey objects on it (which can be the case when using reflected tables with MySQL), or if the join condition cannot be expressed by a simple foreign key relationship, use the primaryjoin and possibly secondaryjoin conditions to create the appropriate relationship.

In this example we create a relationship boston_addresses which will only load the user addresses with a city of “Boston”:

class User(object):
    pass
class Address(object):
    pass

mapper(Address, addresses_table)
mapper(User, users_table, properties={
    'boston_addresses': relationship(Address, primaryjoin=
                and_(users_table.c.user_id==addresses_table.c.user_id,
                addresses_table.c.city=='Boston'))
})

Many to many relationships can be customized by one or both of primaryjoin and secondaryjoin, shown below with just the default many-to-many relationship explicitly set:

class User(object):
    pass
class Keyword(object):
    pass
mapper(Keyword, keywords_table)
mapper(User, users_table, properties={
    'keywords': relationship(Keyword, secondary=userkeywords_table,
        primaryjoin=users_table.c.user_id==userkeywords_table.c.user_id,
        secondaryjoin=userkeywords_table.c.keyword_id==keywords_table.c.keyword_id
        )
})

Specifying Foreign Keys

When using primaryjoin and secondaryjoin, SQLAlchemy also needs to be aware of which columns in the relationship reference the other. In most cases, a Table construct will have ForeignKey constructs which take care of this; however, in the case of reflected tables on a database that does not report FKs (like MySQL ISAM) or when using join conditions on columns that don’t have foreign keys, the relationship() needs to be told specifically which columns are “foreign” using the foreign_keys collection:

mapper(Address, addresses_table)
mapper(User, users_table, properties={
    'addresses': relationship(Address, primaryjoin=
                users_table.c.user_id==addresses_table.c.user_id,
                foreign_keys=[addresses_table.c.user_id])
})

Building Query-Enabled Properties

Very ambitious custom join conditions may fail to be directly persistable, and in some cases may not even load correctly. To remove the persistence part of the equation, use the flag viewonly=True on the relationship(), which establishes it as a read-only attribute (data written to the collection will be ignored on flush()). However, in extreme cases, consider using a regular Python property in conjunction with Query as follows:

class User(object):
    def _get_addresses(self):
        return object_session(self).query(Address).with_parent(self).filter(...).all()
    addresses = property(_get_addresses)

Multiple Relationships against the Same Parent/Child

Theres no restriction on how many times you can relate from parent to child. SQLAlchemy can usually figure out what you want, particularly if the join conditions are straightforward. Below we add a newyork_addresses attribute to complement the boston_addresses attribute:

mapper(User, users_table, properties={
    'boston_addresses': relationship(Address, primaryjoin=
                and_(users_table.c.user_id==addresses_table.c.user_id,
                addresses_table.c.city=='Boston')),
    'newyork_addresses': relationship(Address, primaryjoin=
                and_(users_table.c.user_id==addresses_table.c.user_id,
                addresses_table.c.city=='New York')),
})

Rows that point to themselves / Mutually Dependent Rows

This is a very specific case where relationship() must perform an INSERT and a second UPDATE in order to properly populate a row (and vice versa an UPDATE and DELETE in order to delete without violating foreign key constraints). The two use cases are:

  • A table contains a foreign key to itself, and a single row will have a foreign key value pointing to its own primary key.
  • Two tables each contain a foreign key referencing the other table, with a row in each table referencing the other.

For example:

          user
---------------------------------
user_id    name   related_user_id
   1       'ed'          1

Or:

             widget                                                  entry
-------------------------------------------             ---------------------------------
widget_id     name        favorite_entry_id             entry_id      name      widget_id
   1       'somewidget'          5                         5       'someentry'     1

In the first case, a row points to itself. Technically, a database that uses sequences such as PostgreSQL or Oracle can INSERT the row at once using a previously generated value, but databases which rely upon autoincrement-style primary key identifiers cannot. The relationship() always assumes a “parent/child” model of row population during flush, so unless you are populating the primary key/foreign key columns directly, relationship() needs to use two statements.

In the second case, the “widget” row must be inserted before any referring “entry” rows, but then the “favorite_entry_id” column of that “widget” row cannot be set until the “entry” rows have been generated. In this case, it’s typically impossible to insert the “widget” and “entry” rows using just two INSERT statements; an UPDATE must be performed in order to keep foreign key constraints fulfilled. The exception is if the foreign keys are configured as “deferred until commit” (a feature some databases support) and if the identifiers were populated manually (again essentially bypassing relationship()).

To enable the UPDATE after INSERT / UPDATE before DELETE behavior on relationship(), use the post_update flag on one of the relationships, preferably the many-to-one side:

mapper(Widget, widget, properties={
    'entries':relationship(Entry, primaryjoin=widget.c.widget_id==entry.c.widget_id),
    'favorite_entry':relationship(Entry, primaryjoin=widget.c.favorite_entry_id==entry.c.entry_id, post_update=True)
})

When a structure using the above mapping is flushed, the “widget” row will be INSERTed minus the “favorite_entry_id” value, then all the “entry” rows will be INSERTed referencing the parent “widget” row, and then an UPDATE statement will populate the “favorite_entry_id” column of the “widget” table (it’s one row at a time for the time being).

Mutable Primary Keys / Update Cascades

When the primary key of an entity changes, related items which reference the primary key must also be updated as well. For databases which enforce referential integrity, it’s required to use the database’s ON UPDATE CASCADE functionality in order to propagate primary key changes to referenced foreign keys - the values cannot be out of sync for any moment.

For databases that don’t support this, such as SQLite and MySQL without their referential integrity options turned on, the passive_updates flag can be set to False, most preferably on a one-to-many or many-to-many relationship(), which instructs SQLAlchemy to issue UPDATE statements individually for objects referenced in the collection, loading them into memory if not already locally present. The passive_updates flag can also be False in conjunction with ON UPDATE CASCADE functionality, although in that case the unit of work will be issuing extra SELECT and UPDATE statements unnecessarily.

A typical mutable primary key setup might look like:

users = Table('users', metadata,
    Column('username', String(50), primary_key=True),
    Column('fullname', String(100)))

addresses = Table('addresses', metadata,
    Column('email', String(50), primary_key=True),
    Column('username', String(50), ForeignKey('users.username', onupdate="cascade")))

class User(object):
    pass
class Address(object):
    pass

# passive_updates=False *only* needed if the database
# does not implement ON UPDATE CASCADE

mapper(User, users, properties={
    'addresses': relationship(Address, passive_updates=False)
})
mapper(Address, addresses)

passive_updates is set to True by default, indicating that ON UPDATE CASCADE is expected to be in place in the usual case for foreign keys that expect to have a mutating parent key.

passive_updates=False may be configured on any direction of relationship, i.e. one-to-many, many-to-one, and many-to-many, although it is much more effective when placed just on the one-to-many or many-to-many side. Configuring the passive_updates=False only on the many-to-one side will have only a partial effect, as the unit of work searches only through the current identity map for objects that may be referencing the one with a mutating primary key, not throughout the database.

The relationship() API

sqlalchemy.orm.relationship(argument, secondary=None, **kwargs)

Provide a relationship of a primary Mapper to a secondary Mapper.

Note

relationship() is historically known as relation() prior to version 0.6.

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

A typical relationship():

mapper(Parent, properties={
  'children': relationship(Children)
})
Parameters:
  • argument – a class or Mapper instance, representing the target of the relationship.
  • secondary – for a many-to-many relationship, specifies the intermediary table. The secondary keyword argument should generally only be used for a table that is not otherwise expressed in any class mapping. In particular, using the Association Object Pattern is generally mutually exclusive with the use of the secondary keyword argument.
  • active_history=False – When True, indicates that the “previous” value for a many-to-one reference should be loaded when replaced, if not already loaded. Normally, history tracking logic for simple many-to-ones only needs to be aware of the “new” value in order to perform a flush. This flag is available for applications that make use of attributes.get_history() which also need to know the “previous” value of the attribute. (New in 0.6.6)
  • backref – indicates the string name of a property to be placed on the related mapper’s class that will handle this relationship in the other direction. The other property will be created automatically when the mappers are configured. Can also be passed as a backref() object to control the configuration of the new relationship.
  • back_populates – Takes a string name and has the same meaning as backref, except the complementing property is not created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate back_populates to this relationship to ensure proper functioning.
  • cascade

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

    Available cascades are:

    • save-update - cascade the Session.add() operation. This cascade applies both to future and past calls to add(), meaning new items added to a collection or scalar relationship get placed into the same session as that of the parent, and also applies to items which have been removed from this relationship but are still part of unflushed history.
    • merge - cascade the merge() operation
    • expunge - cascade the Session.expunge() operation
    • delete - cascade the Session.delete() operation
    • delete-orphan - if an item of the child’s type with no parent is detected, mark it for deletion. Note that this option prevents a pending item of the child’s class from being persisted without a parent present.
    • refresh-expire - cascade the Session.expire() and refresh() operations
    • all - shorthand for “save-update,merge, refresh-expire, expunge, delete”
  • cascade_backrefs=True

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

    That is:

    mapper(A, a_table, properties={
        'bs':relationship(B, backref="a", cascade_backrefs=False)
    })

    If an A() is present in the session, assigning it to the “a” attribute on a transient B() will not place the B() into the session. To set the flag in the other direction, i.e. so that A().bs.append(B()) won’t add a transient A() into the session for a persistent B():

    mapper(A, a_table, properties={
        'bs':relationship(B, 
                backref=backref("a", cascade_backrefs=False)
            )
    })

    cascade_backrefs is new in 0.6.5.

  • collection_class – a class or callable that returns a new list-holding object. will be used in place of a plain list for storing elements. Behavior of this attribute is described in detail at Customizing Collection Access.
  • comparator_factory – a class which extends RelationshipProperty.Comparator which provides custom SQL clause generation for comparison operations.
  • doc – docstring which will be applied to the resulting descriptor.
  • extension – an AttributeExtension instance, or list of extensions, which will be prepended to the list of attribute listeners for the resulting descriptor placed on the class. These listeners will receive append and set events before the operation proceeds, and may be used to halt (via exception throw) or change the value used in the operation.
  • foreign_keys

    a list of columns which are to be used as “foreign key” columns. Normally, relationship() uses the ForeignKey and ForeignKeyConstraint objects present within the mapped or secondary Table to determine the “foreign” side of the join condition. This is used to construct SQL clauses in order to load objects, as well as to “synchronize” values from primary key columns to referencing foreign key columns. The foreign_keys parameter overrides the notion of what’s “foreign” in the table metadata, allowing the specification of a list of Column objects that should be considered part of the foreign key.

    There are only two use cases for foreign_keys - one, when it is not convenient for Table metadata to contain its own foreign key metadata (which should be almost never, unless reflecting a large amount of tables from a MySQL MyISAM schema, or a schema that doesn’t actually have foreign keys on it). The other is for extremely rare and exotic composite foreign key setups where some columns should artificially not be considered as foreign.

  • innerjoin=False – when True, joined eager loads will use an inner join to join against related tables instead of an outer join. The purpose of this option is strictly one of performance, as inner joins generally perform better than outer joins. This flag can be set to True when the relationship references an object via many-to-one using local foreign keys that are not nullable, or when the reference is one-to-one or a collection that is guaranteed to have one or at least one entry.
  • join_depth – when non-None, an integer value indicating how many levels deep “eager” loaders should join on a self-referring or cyclical relationship. The number counts how many times the same Mapper shall be present in the loading condition along a particular join branch. When left at its default of None, eager loaders will stop chaining when they encounter a the same target mapper which is already higher up in the chain. This option applies both to joined- and subquery- eager loaders.
  • lazy=’select’

    specifies how the related items should be loaded. Default value is select. Values include:

    • select - items should be loaded lazily when the property is first accessed, using a separate SELECT statement, or identity map fetch for simple many-to-one references.
    • immediate - items should be loaded as the parents are loaded, using a separate SELECT statement, or identity map fetch for simple many-to-one references. (new as of 0.6.5)
    • joined - items should be loaded “eagerly” in the same query as that of the parent, using a JOIN or LEFT OUTER JOIN. Whether the join is “outer” or not is determined by the innerjoin parameter.
    • subquery - items should be loaded “eagerly” within the same query as that of the parent, using a second SQL statement which issues a JOIN to a subquery of the original statement.
    • noload - no loading should occur at any time. This is to support “write-only” attributes, or attributes which are populated in some manner specific to the application.
    • dynamic - the attribute will return a pre-configured Query object for all read operations, onto which further filtering operations can be applied before iterating the results. The dynamic collection supports a limited set of mutation operations, allowing append() and remove(). Changes to the collection will not be visible until flushed to the database, where it is then refetched upon iteration.
    • True - a synonym for ‘select’
    • False - a synonyn for ‘joined’
    • None - a synonym for ‘noload’

    Detailed discussion of loader strategies is at Relationship Loading Techniques.

  • load_on_pending=False

    Indicates loading behavior for transient or pending parent objects.

    When set to True, causes the lazy-loader to issue a query for a parent object that is not persistent, meaning it has never been flushed. This may take effect for a pending object when autoflush is disabled, or for a transient object that has been “attached” to a Session but is not part of its pending collection. Attachment of transient objects to the session without moving to the “pending” state is not a supported behavior at this time.

    Note that the load of related objects on a pending or transient object also does not trigger any attribute change events - no user-defined events will be emitted for these attributes, and if and when the object is ultimately flushed, only the user-specific foreign key attributes will be part of the modified state.

    The load_on_pending flag does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before flush() proceeds. This flag is not not intended for general use.

    New in 0.6.5.

  • order_by – indicates the ordering that should be applied when loading these items.
  • passive_deletes=False

    Indicates loading behavior during delete operations.

    A value of True indicates that unloaded child items should not be loaded during a delete operation on the parent. Normally, when a parent item is deleted, all child items are loaded so that they can either be marked as deleted, or have their foreign key to the parent set to NULL. Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL> rule is in place which will handle updating/deleting child rows on the database side.

    Additionally, setting the flag to the string value ‘all’ will disable the “nulling out” of the child foreign keys, when there is no delete or delete-orphan cascade enabled. This is typically used when a triggering or error raise scenario is in place on the database side. Note that the foreign key attributes on in-session child objects will not be changed after a flush occurs so this is a very special use-case setting.

  • passive_updates=True

    Indicates loading and INSERT/UPDATE/DELETE behavior when the source of a foreign key value changes (i.e. an “on update” cascade), which are typically the primary key columns of the source row.

    When True, it is assumed that ON UPDATE CASCADE is configured on the foreign key in the database, and that the database will handle propagation of an UPDATE from a source column to dependent rows. Note that with databases which enforce referential integrity (i.e. PostgreSQL, MySQL with InnoDB tables), ON UPDATE CASCADE is required for this operation. The relationship() will update the value of the attribute on related items which are locally present in the session during a flush.

    When False, it is assumed that the database does not enforce referential integrity and will not be issuing its own CASCADE operation for an update. The relationship() will issue the appropriate UPDATE statements to the database in response to the change of a referenced key, and items locally present in the session during a flush will also be refreshed.

    This flag should probably be set to False if primary key changes are expected and the database in use doesn’t support CASCADE (i.e. SQLite, MySQL MyISAM tables).

    Also see the passive_updates flag on mapper().

    A future SQLAlchemy release will provide a “detect” feature for this flag.

  • post_update – this indicates that the relationship should be handled by a second UPDATE statement after an INSERT or before a DELETE. Currently, it also will issue an UPDATE after the instance was UPDATEd as well, although this technically should be improved. This flag is used to handle saving bi-directional dependencies between two individual rows (i.e. each row references the other), where it would otherwise be impossible to INSERT or DELETE both rows fully since one row exists before the other. Use this flag when a particular mapping arrangement will incur two rows that are dependent on each other, such as a table that has a one-to-many relationship to a set of child rows, and also has a column that references a single child row within that list (i.e. both tables contain a foreign key to each other). If a flush() operation returns an error that a “cyclical dependency” was detected, this is a cue that you might want to use post_update to “break” the cycle.
  • primaryjoin – a ColumnElement (i.e. WHERE criterion) that will be used as the primary join of this child object against the parent object, or in a many-to-many relationship the join of the primary object to the association table. By default, this value is computed based on the foreign key relationships of the parent and child tables (or association table).
  • remote_side – used for self-referential relationships, indicates the column or list of columns that form the “remote side” of the relationship.
  • secondaryjoin – a ColumnElement (i.e. WHERE criterion) that will be used as the join of an association table to the child object. By default, this value is computed based on the foreign key relationships of the association and child tables.
  • single_parent=(True|False) – when True, installs a validator which will prevent objects from being associated with more than one parent at a time. This is used for many-to-one or many-to-many relationships that should be treated either as one-to-one or one-to-many. Its usage is optional unless delete-orphan cascade is also set on this relationship(), in which case its required (new in 0.5.2).
  • uselist=(True|False) – a boolean that indicates if this property should be loaded as a list or a scalar. In most cases, this value is determined automatically by relationship(), based on the type and direction of the relationship - one to many forms a list, many to one forms a scalar, many to many is a list. If a scalar is desired where normally a list would be present, such as a bi-directional one-to-one relationship, set uselist to False.
  • viewonly=False – when set to True, the relationship is used only for loading objects within the relationship, and has no effect on the unit-of-work flush process. Relationships with viewonly can specify any kind of join conditions to provide additional views of related objects onto a parent object. Note that the functionality of a viewonly relationship has its limits - complicated join conditions may not compile into eager or lazy loaders properly. If this is the case, use an alternative method.
sqlalchemy.orm.backref(name, **kwargs)

Create a back reference with explicit arguments, which are the same arguments one can send to relationship().

Used with the backref keyword argument to relationship() in place of a string argument.

sqlalchemy.orm.relation(*arg, **kw)

A synonym for relationship().