Collections are not limited to lists. Sets, mutable sequences and almost any
other Python object that can act as a container can be used in place of the
-default list, by specifying the ``collection_class`` option on
+default list, by specifying the :paramref:`~.relationship.collection_class` option on
:func:`~sqlalchemy.orm.relationship`::
class Parent(Base):
+.. _loading_toplevel:
+
.. currentmodule:: sqlalchemy.orm
Relationship Loading Techniques
absolutely ensure that it does not affect the end result of the query, only
the way collections and related objects are loaded, no matter what the format of the query is.
+.. _what_kind_of_loading:
+
What Kind of Loading to Use ?
-----------------------------
* When using joined loading, the load of 100 objects will emit only one SQL statement. The join
will be a LEFT OUTER JOIN, and the total number of rows will be equal to 100 in all cases.
If you know that each parent definitely has a child (i.e. the foreign
- key reference is NOT NULL), the joined load can be configured with ``innerjoin=True``, which is
+ key reference is NOT NULL), the joined load can be configured with
+ :paramref:`~.relationship.innerjoin` set to ``True``, which is
usually specified within the :func:`~sqlalchemy.orm.relationship`. For a load of objects where
there are many possible target references which may have not been loaded already, joined loading
with an INNER JOIN is extremely efficient.
parent_id = Column(Integer, ForeignKey('parent.id'))
To establish a bidirectional relationship in one-to-many, where the "reverse"
-side is a many to one, specify the ``backref`` option::
+side is a many to one, specify the :paramref:`~.relationship.backref` option::
class Parent(Base):
__tablename__ = 'parent'
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
-Bidirectional behavior is achieved by specifying ``backref="parents"``,
-which will place a one-to-many collection on the ``Child`` class::
+Bidirectional behavior is achieved by setting
+:paramref:`~.relationship.backref` to the value ``"parents"``, which
+will place a one-to-many collection on the ``Child`` class::
class Parent(Base):
__tablename__ = 'parent'
child_id = Column(Integer, ForeignKey('child.id'))
child = relationship("Child", backref="parents")
+.. _relationships_one_to_one:
+
One To One
~~~~~~~~~~~
One To One is essentially a bidirectional relationship with a scalar
-attribute on both sides. To achieve this, the ``uselist=False`` flag indicates
+attribute on both sides. To achieve this, the :paramref:`~.relationship.uselist` 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::
~~~~~~~~~~~~~
Many to Many adds an association table between two classes. The association
-table is indicated by the ``secondary`` argument to
+table is indicated by the :paramref:`~.relationship.secondary` argument to
:func:`.relationship`. Usually, the :class:`.Table` uses the :class:`.MetaData`
object associated with the declarative base class, so that the :class:`.ForeignKey`
directives can locate the remote tables with which to link::
id = Column(Integer, primary_key=True)
For a bidirectional relationship, both sides of the relationship contain a
-collection. The ``backref`` keyword will automatically use
-the same ``secondary`` argument for the reverse relationship::
+collection. The :paramref:`~.relationship.backref` keyword will automatically use
+the same :paramref:`~.relationship.secondary` argument for the reverse relationship::
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
-The ``secondary`` argument of :func:`.relationship` also accepts a callable
+The :paramref:`~.relationship.secondary` argument of :func:`.relationship` also accepts a callable
that returns the ultimate argument, which is evaluated only when mappers are
first used. Using this, we can define the ``association_table`` at a later
point, as long as it's available to the callable after all module initialization
Deleting Rows from the Many to Many Table
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-A behavior which is unique to the ``secondary`` argument to :func:`.relationship`
+A behavior which is unique to the :paramref:`~.relationship.secondary` argument to :func:`.relationship`
is that the :class:`.Table` which is specified here is automatically subject
to INSERT and DELETE statements, as objects are added or removed from the collection.
There is **no need to delete from this table manually**. The act of removing a
directive on :func:`.relationship`; see :ref:`passive_deletes` for more details
on this.
-Note again, these behaviors are *only* relevant to the ``secondary`` option
+Note again, these behaviors are *only* relevant to the :paramref:`~.relationship.secondary` option
used with :func:`.relationship`. If dealing with association tables that
-are mapped explicitly and are *not* present in the ``secondary`` option
+are mapped explicitly and are *not* present in the :paramref:`~.relationship.secondary` option
of a relevant :func:`.relationship`, cascade rules can be used instead
to automatically delete entities in reaction to a related entity being
deleted - see :ref:`unitofwork_cascades` for information on this feature.
Association Object
~~~~~~~~~~~~~~~~~~
-The association object pattern is a variant on many-to-many: it's
-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. Below we illustrate an association table mapped to the
-``Association`` class which includes a column called ``extra_data``,
-which is a string value that is stored along with each association
-between ``Parent`` and ``Child``::
+The association object pattern is a variant on many-to-many: it's used
+when your association table contains additional columns beyond those
+which are foreign keys to the left and right tables. Instead of using
+the :paramref:`~.relationship.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. Below we illustrate
+an association table mapped to the ``Association`` class which
+includes a column called ``extra_data``, which is a string value that
+is stored along with each association between ``Parent`` and
+``Child``::
class Association(Base):
__tablename__ = 'association'
.. note::
- When using the association object pattern, it is
- advisable that the association-mapped table not be used
- as the ``secondary`` argument on a :func:`.relationship`
- elsewhere, unless that :func:`.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.
+ When using the association object pattern, it is advisable that the
+ association-mapped table not be used as the
+ :paramref:`~.relationship.secondary` argument on a
+ :func:`.relationship` elsewhere, unless that :func:`.relationship`
+ contains the option :paramref:`~.relationship.viewonly` set to
+ ``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.
.. _self_referential:
AND node_1.data = ?
['subchild1', 'child2']
-:meth:`.Query.join` also includes a feature known as ``aliased=True`` that
-can shorten the verbosity self-referential joins, at the expense
-of query flexibility. This feature
-performs a similar "aliasing" step to that above, without the need for an
-explicit entity. Calls to :meth:`.Query.filter` and similar subsequent to
-the aliased join will **adapt** the ``Node`` entity to be that of the alias:
+:meth:`.Query.join` also includes a feature known as
+:paramref:`.Query.join.aliased` that can shorten the verbosity self-
+referential joins, at the expense of query flexibility. This feature
+performs a similar "aliasing" step to that above, without the need for
+an explicit entity. Calls to :meth:`.Query.filter` and similar
+subsequent to the aliased join will **adapt** the ``Node`` entity to
+be that of the alias:
.. sourcecode:: python+sql
WHERE node.data = ? AND node_1.data = ?
['subchild1', 'child2']
-To add criterion to multiple points along a longer join, add ``from_joinpoint=True``
-to the additional :meth:`~.Query.join` calls:
+To add criterion to multiple points along a longer join, add
+:paramref:`.Query.join.from_joinpoint` to the additional
+:meth:`~.Query.join` calls:
.. sourcecode:: python+sql
reset_joinpoint().\
filter(Node.data == 'bar')
-For an example of using ``aliased=True`` to arbitrarily join along a chain of self-referential
-nodes, see :ref:`examples_xmlpersistence`.
+For an example of using :paramref:`.Query.join.aliased` to
+arbitrarily join along a chain of self-referential nodes, see
+:ref:`examples_xmlpersistence`.
+
+.. _self_referential_eager_loading:
Configuring Self-Referential Eager Loading
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
joining. However, to use eager loading with a self-referential relationship,
SQLAlchemy needs to be told how many levels deep it should join and/or query;
otherwise the eager load will not take place at all. This depth setting is
-configured via ``join_depth``:
+configured via :paramref:`~.relationships.join_depth`:
.. sourcecode:: python+sql
Linking Relationships with Backref
----------------------------------
-The ``backref`` keyword argument was first introduced in :ref:`ormtutorial_toplevel`, and has been
+The :paramref:`~.relationship.backref` keyword argument was first introduced in :ref:`ormtutorial_toplevel`, and has been
mentioned throughout many of the examples here. What does it actually do ? Let's start
with the canonical ``User`` and ``Address`` scenario::
``User.addresses``. It also establishes a ``.user`` attribute on ``Address`` which will
refer to the parent ``User`` object.
-In fact, the ``backref`` keyword is only a common shortcut for placing a second
-``relationship`` onto the ``Address`` mapping, including the establishment
+In fact, the :paramref:`~.relationship.backref` keyword is only a common shortcut for placing a second
+:func:`.relationship` onto the ``Address`` mapping, including the establishment
of an event listener on both sides which will mirror attribute operations
in both directions. The above configuration is equivalent to::
user = relationship("User", back_populates="addresses")
Above, we add a ``.user`` relationship to ``Address`` explicitly. On
-both relationships, the ``back_populates`` directive tells each relationship
+both relationships, the :paramref:`~.relationship.back_populates` directive tells each relationship
about the other one, indicating that they should establish "bidirectional"
behavior between each other. The primary effect of this configuration
is that the relationship adds event handlers to both attributes
occurs entirely in Python without any interaction with the SQL database.
Without this behavior, the proper state would be apparent on both sides once the
data has been flushed to the database, and later reloaded after a commit or
-expiration operation occurs. The ``backref``/``back_populates`` behavior has the advantage
+expiration operation occurs. The :paramref:`~.relationship.backref`/:paramref:`~.relationship.back_populates` behavior has the advantage
that common bidirectional operations can reflect the correct state without requiring
a database round trip.
-Remember, when the ``backref`` keyword is used on a single relationship, it's
+Remember, when the :paramref:`~.relationship.backref` keyword is used on a single relationship, it's
exactly the same as if the above two relationships were created individually
-using ``back_populates`` on each.
+using :paramref:`~.relationship.back_populates` on each.
Backref Arguments
~~~~~~~~~~~~~~~~~~
-We've established that the ``backref`` keyword is merely a shortcut for building
+We've established that the :paramref:`~.relationship.backref` keyword is merely a shortcut for building
two individual :func:`.relationship` constructs that refer to each other. Part of
the behavior of this shortcut is that certain configurational arguments applied to
the :func:`.relationship`
will also be applied to the other direction - namely those arguments that describe
the relationship at a schema level, and are unlikely to be different in the reverse
direction. The usual case
-here is a many-to-many :func:`.relationship` that has a ``secondary`` argument,
-or a one-to-many or many-to-one which has a ``primaryjoin`` argument (the
-``primaryjoin`` argument is discussed in :ref:`relationship_primaryjoin`). Such
+here is a many-to-many :func:`.relationship` that has a :paramref:`~.relationship.secondary` argument,
+or a one-to-many or many-to-one which has a :paramref:`~.relationship.primaryjoin` argument (the
+:paramref:`~.relationship.primaryjoin` argument is discussed in :ref:`relationship_primaryjoin`). Such
as if we limited the list of ``Address`` objects to those which start with "tony"::
from sqlalchemy import Integer, ForeignKey, String, Column
"user".id = address.user_id AND address.email LIKE :email_1 || '%%'
>>>
-This reuse of arguments should pretty much do the "right thing" - it uses
-only arguments that are applicable, and in the case of a many-to-many
-relationship, will reverse the usage of ``primaryjoin`` and ``secondaryjoin``
-to correspond to the other direction (see the example in :ref:`self_referential_many_to_many`
-for this).
-
-It's very often the case however that we'd like to specify arguments that
-are specific to just the side where we happened to place the "backref".
-This includes :func:`.relationship` arguments like ``lazy``, ``remote_side``,
-``cascade`` and ``cascade_backrefs``. For this case we use the :func:`.backref`
-function in place of a string::
+This reuse of arguments should pretty much do the "right thing" - it
+uses only arguments that are applicable, and in the case of a many-to-
+many relationship, will reverse the usage of
+:paramref:`~.relationship.primaryjoin` and
+:paramref:`~.relationship.secondaryjoin` to correspond to the other
+direction (see the example in :ref:`self_referential_many_to_many` for
+this).
+
+It's very often the case however that we'd like to specify arguments
+that are specific to just the side where we happened to place the
+"backref". This includes :func:`.relationship` arguments like
+:paramref:`~.relationship.lazy`,
+:paramref:`~.relationship.remote_side`,
+:paramref:`~.relationship.cascade` and
+:paramref:`~.relationship.cascade_backrefs`. For this case we use
+the :func:`.backref` function in place of a string::
# <other imports>
from sqlalchemy.orm import backref
One Way Backrefs
~~~~~~~~~~~~~~~~~
-An unusual case is that of the "one way backref". This is where the "back-populating"
-behavior of the backref is only desirable in one direction. An example of this
-is a collection which contains a filtering ``primaryjoin`` condition. We'd like to append
-items to this collection as needed, and have them populate the "parent" object on the
-incoming object. However, we'd also like to have items that are not part of the collection,
-but still have the same "parent" association - these items should never be in the
-collection.
-
-Taking our previous example, where we established a ``primaryjoin`` that limited the
-collection only to ``Address`` objects whose email address started with the word ``tony``,
-the usual backref behavior is that all items populate in both directions. We wouldn't
-want this behavior for a case like the following::
+An unusual case is that of the "one way backref". This is where the
+"back-populating" behavior of the backref is only desirable in one
+direction. An example of this is a collection which contains a
+filtering :paramref:`~.relationship.primaryjoin` condition. We'd
+like to append items to this collection as needed, and have them
+populate the "parent" object on the incoming object. However, we'd
+also like to have items that are not part of the collection, but still
+have the same "parent" association - these items should never be in
+the collection.
+
+Taking our previous example, where we established a
+:paramref:`~.relationship.primaryjoin` that limited the collection
+only to ``Address`` objects whose email address started with the word
+``tony``, the usual backref behavior is that all items populate in
+both directions. We wouldn't want this behavior for a case like the
+following::
>>> u1 = User()
>>> a1 = Address(email='mary')
collection will hit the database on next access and no longer have this ``Address`` object
present, due to the filtering condition. But we can do away with this unwanted side
of the "backref" behavior on the Python side by using two separate :func:`.relationship` constructs,
-placing ``back_populates`` only on one side::
+placing :paramref:`~.relationship.back_populates` only on one side::
from sqlalchemy import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative import declarative_base
>>> a2 in u1.addresses
False
-Of course, we've disabled some of the usefulness of ``backref`` here, in that
-when we do append an ``Address`` that corresponds to the criteria of ``email.startswith('tony')``,
-it won't show up in the ``User.addresses`` collection until the session is flushed,
-and the attributes reloaded after a commit or expire operation. While we could
-consider an attribute event that checks this criterion in Python, this starts
-to cross the line of duplicating too much SQL behavior in Python. The backref behavior
-itself is only a slight transgression of this philosophy - SQLAlchemy tries to keep
-these to a minimum overall.
+Of course, we've disabled some of the usefulness of
+:paramref:`~.relationship.backref` here, in that when we do append an
+``Address`` that corresponds to the criteria of
+``email.startswith('tony')``, it won't show up in the
+``User.addresses`` collection until the session is flushed, and the
+attributes reloaded after a commit or expire operation. While we
+could consider an attribute event that checks this criterion in
+Python, this starts to cross the line of duplicating too much SQL
+behavior in Python. The backref behavior itself is only a slight
+transgression of this philosophy - SQLAlchemy tries to keep these to a
+minimum overall.
.. _relationship_configure_joins:
.. versionchanged:: 0.8
:func:`.relationship` can resolve ambiguity between foreign key targets on the
- basis of the ``foreign_keys`` argument alone; the ``primaryjoin`` argument is no
- longer needed in this situation.
+ basis of the ``foreign_keys`` argument alone; the :paramref:`~.relationship.primaryjoin`
+ argument is no longer needed in this situation.
.. _relationship_primaryjoin:
:func:`.and_` are automatically available in the evaluated namespace of a string
:func:`.relationship` argument.
-The custom criteria we use in a ``primaryjoin`` is generally only significant
-when SQLAlchemy is rendering SQL in order to load or represent this relationship.
-That is, it's used
-in the SQL statement that's emitted in order to perform a per-attribute lazy load, or when a join is
-constructed at query time, such as via :meth:`.Query.join`, or via the eager "joined" or "subquery"
-styles of loading. When in-memory objects are being manipulated, we can place any ``Address`` object
-we'd like into the ``boston_addresses`` collection, regardless of what the value of the ``.city``
-attribute is. The objects will remain present in the collection until the attribute is expired
-and re-loaded from the database where the criterion is applied. When
-a flush occurs, the objects inside of ``boston_addresses`` will be flushed unconditionally, assigning
-value of the primary key ``user.id`` column onto the foreign-key-holding ``address.user_id`` column
-for each row. The ``city`` criteria has no effect here, as the flush process only cares about synchronizing primary
-key values into referencing foreign key values.
+The custom criteria we use in a :paramref:`~.relationship.primaryjoin`
+is generally only significant when SQLAlchemy is rendering SQL in
+order to load or represent this relationship. That is, it's used in
+the SQL statement that's emitted in order to perform a per-attribute
+lazy load, or when a join is constructed at query time, such as via
+:meth:`.Query.join`, or via the eager "joined" or "subquery" styles of
+loading. When in-memory objects are being manipulated, we can place
+any ``Address`` object we'd like into the ``boston_addresses``
+collection, regardless of what the value of the ``.city`` attribute
+is. The objects will remain present in the collection until the
+attribute is expired and re-loaded from the database where the
+criterion is applied. When a flush occurs, the objects inside of
+``boston_addresses`` will be flushed unconditionally, assigning value
+of the primary key ``user.id`` column onto the foreign-key-holding
+``address.user_id`` column for each row. The ``city`` criteria has no
+effect here, as the flush process only cares about synchronizing
+primary key values into referencing foreign key values.
.. _relationship_custom_foreign:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Another element of the primary join condition is how those columns
-considered "foreign" are determined. Usually, some subset
-of :class:`.Column` objects will specify :class:`.ForeignKey`, or otherwise
-be part of a :class:`.ForeignKeyConstraint` that's relevant to the join condition.
-:func:`.relationship` looks to this foreign key status as it decides
-how it should load and persist data for this relationship. However, the
-``primaryjoin`` argument can be used to create a join condition that
-doesn't involve any "schema" level foreign keys. We can combine ``primaryjoin``
-along with ``foreign_keys`` and ``remote_side`` explicitly in order to
+considered "foreign" are determined. Usually, some subset of
+:class:`.Column` objects will specify :class:`.ForeignKey`, or
+otherwise be part of a :class:`.ForeignKeyConstraint` that's relevant
+to the join condition. :func:`.relationship` looks to this foreign key
+status as it decides how it should load and persist data for this
+relationship. However, the :paramref:`~.relationship.primaryjoin`
+argument can be used to create a join condition that doesn't involve
+any "schema" level foreign keys. We can combine
+:paramref:`~.relationship.primaryjoin` along with
+:paramref:`~.relationship.foreign_keys` and
+:paramref:`~.relationship.remote_side` explicitly in order to
establish such a join.
Below, a class ``HostEntry`` joins to itself, equating the string ``content``
ON host_entry_1.ip_address = CAST(host_entry.content AS INET)
An alternative syntax to the above is to use the :func:`.foreign` and
-:func:`.remote` :term:`annotations`, inline within the ``primaryjoin`` expression.
+:func:`.remote` :term:`annotations`, inline within the :paramref:`~.relationship.primaryjoin` expression.
This syntax represents the annotations that :func:`.relationship` normally
-applies by itself to the join condition given the ``foreign_keys`` and
-``remote_side`` arguments; the functions are provided in the API in the
+applies by itself to the join condition given the :paramref:`~.relationship.foreign_keys` and
+:paramref:`~.relationship.remote_side` arguments; the functions are provided in the API in the
rare case that :func:`.relationship` can't determine the exact location
of these features on its own::
Self-Referential Many-to-Many Relationship
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Many to many relationships can be customized by one or both of ``primaryjoin``
-and ``secondaryjoin`` - the latter is significant for a relationship that
-specifies a many-to-many reference using the ``secondary`` argument.
-A common situation which involves the usage of ``primaryjoin`` and ``secondaryjoin``
+Many to many relationships can be customized by one or both of :paramref:`~.relationship.primaryjoin`
+and :paramref:`~.relationship.secondaryjoin` - the latter is significant for a relationship that
+specifies a many-to-many reference using the :paramref:`~.relationship.secondary` argument.
+A common situation which involves the usage of :paramref:`~.relationship.primaryjoin` and :paramref:`~.relationship.secondaryjoin`
is when establishing a many-to-many relationship from a class to itself, as shown below::
from sqlalchemy import Integer, ForeignKey, String, Column, Table
)
Where above, SQLAlchemy can't know automatically which columns should connect
-to which for the ``right_nodes`` and ``left_nodes`` relationships. The ``primaryjoin``
-and ``secondaryjoin`` arguments establish how we'd like to join to the association table.
+to which for the ``right_nodes`` and ``left_nodes`` relationships. The :paramref:`~.relationship.primaryjoin`
+and :paramref:`~.relationship.secondaryjoin` arguments establish how we'd like to join to the association table.
In the Declarative form above, as we are declaring these conditions within the Python
block that corresponds to the ``Node`` class, the ``id`` variable is available directly
-as the ``Column`` object we wish to join with.
+as the :class:`.Column` object we wish to join with.
A classical mapping situation here is similar, where ``node_to_node`` can be joined
to ``node.c.id``::
)})
-Note that in both examples, the ``backref`` keyword specifies a ``left_nodes``
-backref - when :func:`.relationship` creates the second relationship in the reverse
-direction, it's smart enough to reverse the ``primaryjoin`` and ``secondaryjoin`` arguments.
+Note that in both examples, the :paramref:`~.relationship.backref`
+keyword specifies a ``left_nodes`` backref - when
+:func:`.relationship` creates the second relationship in the reverse
+direction, it's smart enough to reverse the
+:paramref:`~.relationship.primaryjoin` and
+:paramref:`~.relationship.secondaryjoin` arguments.
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
+the equation, use the flag :paramref:`~.relationship.viewonly` on the
:func:`~sqlalchemy.orm.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 :class:`~sqlalchemy.orm.query.Query` as follows:
+conjunction with :class:`.Query` as follows:
.. sourcecode:: python+sql
:func:`~sqlalchemy.orm.relationship`).
To enable the usage of a supplementary UPDATE statement,
-we use the ``post_update`` option
+we use the :paramref:`~.relationship.post_update` option
of :func:`.relationship`. This specifies that the linkage between the
two rows should be created using an UPDATE statement after both rows
have been INSERTED; it also causes the rows to be de-associated with
be placed on just *one* of the relationships, preferably the
many-to-one side. Below we illustrate
a complete example, including two :class:`.ForeignKey` constructs, one which
-specifies ``use_alter=True`` to help with emitting CREATE TABLE statements::
+specifies :paramref:`~.ForeignKey.use_alter` to help with emitting CREATE TABLE statements::
from sqlalchemy import Integer, ForeignKey, Column
from sqlalchemy.ext.declarative import declarative_base
The above mapping features a composite :class:`.ForeignKeyConstraint`
bridging the ``widget_id`` and ``favorite_entry_id`` columns. To ensure
that ``Widget.widget_id`` remains an "autoincrementing" column we specify
-``autoincrement='ignore_fk'`` on :class:`.Column`, and additionally on each
+:paramref:`~.Column.autoincrement` to the value ``"ignore_fk"``
+on :class:`.Column`, and additionally on each
:func:`.relationship` we must limit those columns considered as part of
the foreign key for the purposes of joining and cross-population.
-.. versionadded:: 0.7.4
- ``autoincrement='ignore_fk'`` on :class:`.Column`\ .
-
.. _passive_updates:
Mutable Primary Keys / Update Cascades
on a one-to-many relationship. Setting it on a many-to-one or
many-to-many relationship is more awkward; for this use case,
SQLAlchemy requires that the :func:`~sqlalchemy.orm.relationship`
- be configured with the ``single_parent=True`` function, which
+ be configured with the :paramref:`~.relationship.single_parent` argument,
establishes Python-side validation that ensures the object
is associated with only one parent at a time.
>>> i1 in session
True
-This behavior can be disabled using the ``cascade_backrefs`` flag::
+This behavior can be disabled using the :paramref:`~.relationship.cascade_backrefs` flag::
mapper(Order, order_table, properties={
'items' : relationship(Item, backref='order',
()
{stop}4
+.. _orm_tutorial_relationship:
+
Building a Relationship
=======================
the ``ON DELETE CASCADE`` functionality of the relational database.
See :ref:`passive_deletes` for details.
+.. _orm_tutorial_many_to_many:
+
Building a Many To Many Relationship
====================================
mymetadata = MetaData()
Base = declarative_base(metadata=mymetadata)
+
+.. _declarative_configuring_relationships:
+
Configuring Relationships
=========================
+.. _declarative_many_to_many:
Configuring Many-to-Many Relationships
======================================
def relationship(argument, secondary=None, **kwargs):
- """Provide a relationship of a primary Mapper to a secondary Mapper.
+ """Provide a relationship between two mapped classes.
This corresponds to a parent-child or associative table relationship. The
constructed class is an instance of :class:`.RelationshipProperty`.
id = Column(Integer, primary_key=True)
children = relationship("Child", order_by="Child.id")
- A full array of examples and reference documentation regarding
- :func:`.relationship` is at :ref:`relationship_config_toplevel`.
+ .. seealso::
+
+ :ref:`relationship_config_toplevel` - Full introductory and reference
+ documentation for :func:`.relationship`.
+
+ :ref:`orm_tutorial_relationship` - ORM tutorial introduction.
:param argument:
a mapped class, or actual :class:`.Mapper` instance, representing the
target of the relationship.
- ``argument`` may also be passed as a callable function
+ :paramref:`~.relationship.argument` may also be passed as a callable function
which is evaluated at mapper initialization time, and may be passed as a
Python-evaluable string when using Declarative.
+ .. seealso::
+
+ :ref:`declarative_configuring_relationships` - further detail
+ on relationship configuration when using Declarative.
+
:param secondary:
for a many-to-many relationship, specifies the intermediary
- table, and is an instance of :class:`.Table`. The ``secondary`` keyword
- argument should generally only
- be used for a table that is not otherwise expressed in any class
- mapping, unless this relationship is declared as view only, otherwise
- conflicting persistence operations can occur.
+ table, and is typically an instance of :class:`.Table`.
+ In less common circumstances, the argument may also be specified
+ as an :class:`.Alias` construct, or even a :class:`.Join` construct.
- ``secondary`` may
+ :paramref:`~.relationship.secondary` may
also be passed as a callable function which is evaluated at
- mapper initialization time.
+ mapper initialization time. When using Declarative, it may also
+ be a string argument noting the name of a :class:`.Table` that is
+ present in the :class:`.MetaData` collection associated with the
+ parent-mapped :class:`.Table`.
+
+ The :paramref:`~.relationship.secondary` keyword argument is typically
+ applied in the case where the intermediary :class:`.Table` is not
+ otherwise exprssed in any direct class mapping. If the "secondary" table
+ is also explicitly mapped elsewhere
+ (e.g. as in :ref:`association_pattern`), one should consider applying
+ the :paramref:`~.relationship.viewonly` flag so that this :func:`.relationship`
+ is not used for persistence operations which may conflict with those
+ of the association object pattern.
+
+ .. seealso::
+
+ :ref:`relationships_many_to_many` - Reference example of "many to many".
+
+ :ref:`orm_tutorial_many_to_many` - ORM tutorial introduction to
+ many-to-many relationships.
+
+ :ref:`self_referential_many_to_many` - Specifics on using many-to-many
+ in a self-referential case.
+
+ :ref:`declarative_many_to_many` - Additional options when using
+ Declarative.
+
+ :ref:`association_pattern` - an alternative to :paramref:`~.relationship.secondary`
+ when composing association table relationships, allowing additional
+ attributes to be specified on the association table.
:param active_history=False:
When ``True``, indicates that the "previous" value for a
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
- :func:`backref` object to control the configuration of the
+ :func:`.backref` object to control the configuration of the
new relationship.
+ .. seealso::
+
+ :ref:`relationships_backref` - Introductory documentation and
+ examples.
+
+ :paramref:`~.relationship.back_populates` - alternative form
+ of backref specification.
+
+ :func:`.backref` - allows control over :func:`.relationship`
+ configuration when using :paramref:`~.relationship.backref`.
+
+
:param back_populates:
- Takes a string name and has the same meaning as ``backref``,
+ Takes a string name and has the same meaning as :paramref:`~.relationship.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``
+ complementing property should also indicate :paramref:`~.relationship.back_populates`
to this relationship to ensure proper functioning.
+ .. seealso::
+
+ :ref:`relationships_backref` - Introductory documentation and
+ examples.
+
+ :paramref:`~.relationship.backref` - alternative form
+ of backref specification.
+
:param cascade:
a comma-separated list of cascade rules which determines how
Session operations should be "cascaded" from parent to child.
* ``save-update`` - cascade the :meth:`.Session.add`
operation. This cascade applies both to future and
- past calls to :meth:`~sqlalchemy.orm.session.Session.add`,
+ past calls to :meth:`.Session.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 :meth:`~sqlalchemy.orm.session.Session.merge`
+ * ``merge`` - cascade the :meth:`.Session.merge`
operation
* ``expunge`` - cascade the :meth:`.Session.expunge`
is configured as NOT NULL
* ``refresh-expire`` - cascade the :meth:`.Session.expire`
- and :meth:`~sqlalchemy.orm.session.Session.refresh` operations
+ and :meth:`.Session.refresh` operations
* ``all`` - shorthand for "save-update,merge, refresh-expire,
expunge, delete"
- See the section :ref:`unitofwork_cascades` for more background
- on configuring cascades.
+ .. seealso::
+
+ :ref:`unitofwork_cascades` - Introductory documentation and
+ examples.
+
+ :ref:`tutorial_delete_cascade` - Tutorial example describing
+ a delete cascade.
:param cascade_backrefs=True:
a boolean value indicating if the ``save-update`` cascade should
)
})
- See the section :ref:`unitofwork_cascades` for more background
- on configuring cascades.
+ .. seealso::
+
+ :ref:`backref_cascade` - Introductory documentation and
+ examples.
:param 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
- :ref:`custom_collections`.
+
+ .. seealso::
+
+ :ref:`custom_collections` - Introductory documentation and
+ examples.
:param comparator_factory:
a class which extends :class:`.RelationshipProperty.Comparator` which
provides custom SQL clause generation for comparison operations.
- :param distinct_target_key=False:
+ .. seealso::
+
+ :class:`.PropComparator` - some detail on redefining comparators
+ at this level.
+
+ :ref:`custom_comparators` - Brief intro to this feature.
+
+
+ :param distinct_target_key=None:
Indicate if a "subquery" eager load should apply the DISTINCT
- keyword to the innermost SELECT statement. When set to ``None``,
+ keyword to the innermost SELECT statement. When left as ``None``,
the DISTINCT keyword will be applied in those cases when the target
columns do not comprise the full primary key of the target table.
When set to ``True``, the DISTINCT keyword is applied to the innermost
SELECT unconditionally.
- This flag defaults as False in 0.8 but will default to None in 0.9.
It may be desirable to set this flag to False when the DISTINCT is
reducing performance of the innermost subquery beyond that of what
duplicate innermost rows may be causing.
- .. versionadded:: 0.8.3 - distinct_target_key allows the
+ .. versionadded:: 0.8.3 - :paramref:`~.relationship.distinct_target_key`
+ allows the
subquery eager loader to apply a DISTINCT modifier to the
innermost SELECT.
+ .. seealso::
+
+ :ref:`loading_toplevel` - includes an introduction to subquery
+ eager loading.
+
:param doc:
docstring which will be applied to the resulting descriptor.
an :class:`.AttributeExtension` instance, or list of extensions,
which will be prepended to the list of attribute listeners for
the resulting descriptor placed on the class.
- **Deprecated.** Please see :class:`.AttributeEvents`.
+
+ .. deprecated:: 0.7 Please see :class:`.AttributeEvents`.
:param foreign_keys:
- a list of columns which are to be used as "foreign key" columns,
- or columns which refer to the value in a remote column, within the
- context of this :func:`.relationship` object's ``primaryjoin``
- condition. That is, if the ``primaryjoin`` condition of this
- :func:`.relationship` is ``a.id == b.a_id``, and the values in ``b.a_id``
- are required to be present in ``a.id``, then the "foreign key" column
- of this :func:`.relationship` is ``b.a_id``.
-
- In normal cases, the ``foreign_keys`` parameter is **not required.**
- :func:`.relationship` will **automatically** determine which columns
- in the ``primaryjoin`` conditition are to be considered "foreign key"
- columns based on those :class:`.Column` objects that specify
- :class:`.ForeignKey`, or are otherwise listed as referencing columns
- in a :class:`.ForeignKeyConstraint` construct. ``foreign_keys`` is only
- needed when:
+
+ a list of columns which are to be used as "foreign key"
+ columns, or columns which refer to the value in a remote
+ column, within the context of this :func:`.relationship`
+ object's :paramref:`~.relationship.primaryjoin` condition.
+ That is, if the :paramref:`~.relationship.primaryjoin`
+ condition of this :func:`.relationship` is ``a.id ==
+ b.a_id``, and the values in ``b.a_id`` are required to be
+ present in ``a.id``, then the "foreign key" column of this
+ :func:`.relationship` is ``b.a_id``.
+
+ In normal cases, the :paramref:`~.relationship.foreign_keys`
+ parameter is **not required.** :func:`.relationship` will
+ automatically determine which columns in the
+ :paramref:`~.relationship.primaryjoin` conditition are to be
+ considered "foreign key" columns based on those
+ :class:`.Column` objects that specify :class:`.ForeignKey`,
+ or are otherwise listed as referencing columns in a
+ :class:`.ForeignKeyConstraint` construct.
+ :paramref:`~.relationship.foreign_keys` is only needed when:
1. There is more than one way to construct a join from the local
table to the remote table, as there are multiple foreign key
.. versionchanged:: 0.8
A multiple-foreign key join ambiguity can be resolved by
- setting the ``foreign_keys`` parameter alone, without the
- need to explicitly set ``primaryjoin`` as well.
+ setting the :paramref:`~.relationship.foreign_keys` parameter alone, without the
+ need to explicitly set :paramref:`~.relationship.primaryjoin` as well.
2. The :class:`.Table` being mapped does not actually have
:class:`.ForeignKey` or :class:`.ForeignKeyConstraint`
was reflected from a database that does not support foreign key
reflection (MySQL MyISAM).
- 3. The ``primaryjoin`` argument is used to construct a non-standard
+ 3. The :paramref:`~.relationship.primaryjoin` argument is used to construct a non-standard
join condition, which makes use of columns or expressions that do
not normally refer to their "parent" column, such as a join condition
expressed by a complex comparison using a SQL function.
- The :func:`.relationship` construct will raise informative error messages
- that suggest the use of the ``foreign_keys`` parameter when presented
- with an ambiguous condition. In typical cases, if :func:`.relationship`
- doesn't raise any exceptions, the ``foreign_keys`` parameter is usually
+ The :func:`.relationship` construct will raise informative
+ error messages that suggest the use of the
+ :paramref:`~.relationship.foreign_keys` parameter when
+ presented with an ambiguous condition. In typical cases,
+ if :func:`.relationship` doesn't raise any exceptions, the
+ :paramref:`~.relationship.foreign_keys` parameter is usually
not needed.
- ``foreign_keys`` may also be passed as a callable function
+ :paramref:`~.relationship.foreign_keys` may also be passed as a callable function
which is evaluated at mapper initialization time, and may be passed as a
Python-evaluable string when using Declarative.
:ref:`relationship_custom_foreign`
:func:`.foreign` - allows direct annotation of the "foreign" columns
- within a ``primaryjoin`` condition.
+ within a :paramref:`~.relationship.primaryjoin` condition.
.. versionadded:: 0.8
The :func:`.foreign` annotation can also be applied
- directly to the ``primaryjoin`` expression, which is an alternate,
+ directly to the :paramref:`~.relationship.primaryjoin` expression, which is an alternate,
more specific system of describing which columns in a particular
- ``primaryjoin`` should be considered "foreign".
+ :paramref:`~.relationship.primaryjoin` should be considered "foreign".
:param info: Optional data dictionary which will be populated into the
:attr:`.MapperProperty.info` attribute of this object.
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 generally one of performance, as inner joins
- generally perform better than outer joins. Another reason can be
- the use of ``with_lockmode``, which does not support outer 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.
+ .. seealso::
+
+ :ref:`what_kind_of_loading` - Discussion of some details of
+ various loader options.
+
:param join_depth:
when non-``None``, an integer value indicating how many levels
deep "eager" loaders should join on a self-referring or cyclical
which is already higher up in the chain. This option applies
both to joined- and subquery- eager loaders.
+ .. seealso::
+
+ :ref:`self_referential_eager_loading` - Introductory documentation
+ and examples.
+
:param lazy='select': specifies
how the related items should be loaded. Default value is
``select``. Values include:
using a separate SELECT statement, or identity map fetch for
simple many-to-one references.
- .. versionadded:: 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``
populated in some manner specific to the application.
* ``dynamic`` - the attribute will return a pre-configured
- :class:`~sqlalchemy.orm.query.Query` object for all read
+ :class:`.Query` object for all read
operations, onto which further filtering operations can be
applied before iterating the results. See
the section :ref:`dynamic_relationship` for more details.
* None - a synonym for 'noload'
- Detailed discussion of loader strategies is at :doc:`/orm/loading`.
+ .. seealso::
+
+ :doc:`/orm/loading` - Full documentation on relationship loader
+ configuration.
+
+ :ref:`dynamic_relationship` - detail on the ``dynamic`` option.
:param load_on_pending=False:
Indicates loading behavior for transient or pending parent objects.
"attached" to a :class:`.Session` but is not part of its pending
collection.
- The load_on_pending flag does not improve behavior
+ The :paramref:`~.relationship.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
+ are present in an ordinary way before a flush proceeds. This flag
is not not intended for general use.
- .. versionadded:: 0.6.5
-
.. seealso::
:meth:`.Session.enable_relationship_loading` - this method establishes
:param order_by:
indicates the ordering that should be applied when loading these
- items. ``order_by`` is expected to refer to one of the :class:`.Column`
+ items. :paramref:`~.relationship.order_by` is expected to refer to one
+ of the :class:`.Column`
objects to which the target class is mapped, or
the attribute itself bound to the target class which refers
to the column.
- ``order_by`` may also be passed as a callable function
+ :paramref:`~.relationship.order_by` may also be passed as a callable function
which is evaluated at mapper initialization time, and may be passed as a
Python-evaluable string when using Declarative.
.. seealso::
- :ref:`passive_updates` - Introductory documentation and
- examples.
+ :ref:`passive_updates` - Introductory documentation and
+ examples.
- :paramref:`.mapper.passive_updates` - a similar flag which
- takes effect for joined-table inheritance mappings.
+ :paramref:`.mapper.passive_updates` - a similar flag which
+ takes effect for joined-table inheritance mappings.
:param post_update:
this indicates that the relationship should be handled by a
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
+ 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.
+ use :paramref:`~.relationship.post_update` to "break" the cycle.
+
+ .. seealso::
+
+ :ref:`post_update` - Introductory documentation and examples.
:param primaryjoin:
a SQL expression that will be used as the primary
foreign key relationships of the parent and child tables (or association
table).
- ``primaryjoin`` may also be passed as a callable function
+ :paramref:`~.relationship.primaryjoin` may also be passed as a callable function
which is evaluated at mapper initialization time, and may be passed as a
Python-evaluable string when using Declarative.
+ .. seealso::
+
+ :ref:`relationship_primaryjoin`
+
:param remote_side:
used for self-referential relationships, indicates the column or
list of columns that form the "remote side" of the relationship.
- ``remote_side`` may also be passed as a callable function
+ :paramref:`.relationship.remote_side` may also be passed as a callable function
which is evaluated at mapper initialization time, and may be passed as a
Python-evaluable string when using Declarative.
more specific system of describing which columns in a particular
``primaryjoin`` should be considered "remote".
+ .. seealso::
+
+ :ref:`self_referential` - in-depth explaination of how
+ :paramref:`~.relationship.remote_side`
+ is used to configure self-referential relationships.
+
+ :func:`.remote` - an annotation function that accomplishes the same
+ purpose as :paramref:`~.relationship.remote_side`, typically
+ when a custom :paramref:`~.relationship.primaryjoin` condition
+ is used.
+
:param query_class:
a :class:`.Query` subclass that will be used as the base of the
"appender query" returned by a "dynamic" relationship, that
otherwise constructed using the :func:`.orm.dynamic_loader`
function.
+ .. seealso::
+
+ :ref:`dynamic_relationship` - Introduction to "dynamic" relationship
+ loaders.
+
:param secondaryjoin:
a SQL expression 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.
- ``secondaryjoin`` may also be passed as a callable function
+ :paramref:`~.relationship.secondaryjoin` may also be passed as a callable function
which is evaluated at mapper initialization time, and may be passed as a
Python-evaluable string when using Declarative.
- :param single_parent=(True|False):
+ .. seealso::
+
+ :ref:`relationship_primaryjoin`
+
+ :param single_parent:
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.
+ should be treated either as one-to-one or one-to-many. Its usage
+ is optional, except for :func:`.relationship` constructs which
+ are many-to-one or many-to-many and also
+ specify the ``delete-orphan`` cascade option. The :func:`.relationship`
+ construct itself will raise an error instructing when this option
+ is required.
+
+ .. seealso::
+
+ :ref:`unitofwork_cascades` - includes detail on when the
+ :paramref:`~.relationship.single_parent` flag may be appropriate.
- :param uselist=(True|False):
+ :param uselist:
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
+ automatically by :func:`.relationship` at mapper configuration
+ time, 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.
+ one-to-one relationship, set :paramref:`~.relationship.uselist` to False.
+
+ The :paramref:`~.relationship.uselist` flag is also available on an
+ existing :func:`.relationship` construct as a read-only attribute, which
+ can be used to determine if this :func:`.relationship` deals with
+ collections or scalar attributes::
+
+ >>> User.addresses.property.uselist
+ True
+
+ .. seealso::
+
+ :ref:`relationships_one_to_one` - Introduction to the "one to one"
+ relationship pattern, which is typically when the
+ :paramref:`~.relationship.uselist` flag is needed.
:param 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.
-
- .. versionchanged:: 0.6
- :func:`relationship` was renamed from its previous name
- :func:`relation`.
+ when set to True, the relationship is used only for loading objects,
+ and not for any persistence operation. A :func:`.relationship`
+ which specifies :paramref:`~.relationship.viewonly` can work
+ with a wider range of SQL operations within the :paramref:`~.relationship.primaryjoin`
+ condition, including operations that feature the use of
+ a variety of comparison operators as well as SQL functions such
+ as :func:`~.sql.expression.cast`. The :paramref:`~.relationship.viewonly`
+ flag is also of general use when defining any kind of :func:`~.relationship`
+ that doesn't represent the full set of related objects, to prevent
+ modifications of the collection from resulting in persistence operations.
- """
+ .. seealso::
+
+ :ref:`relationship_custom_operator` - Introduces the most common
+ use case for :paramref:`~.relationship.viewonly`, that
+ of a non-equality comparison in a :paramref:`~.relationship.primaryjoin`
+ condition.
+ """
return RelationshipProperty(argument, secondary=secondary, **kwargs)
).\\
group_by(included_parts.c.sub_part)
- See also:
+ .. seealso::
- :meth:`.SelectBase.cte`
+ :meth:`.SelectBase.cte`
"""
return self.enable_eagerloads(False).\
.. versionchanged:: 0.7.5
Multiple criteria joined by AND.
- See also:
+ .. seealso::
- :meth:`.Query.filter_by` - filter on keyword expressions.
+ :meth:`.Query.filter_by` - filter on keyword expressions.
"""
for criterion in list(criterion):
entity of the query, or the last entity that was the
target of a call to :meth:`.Query.join`.
- See also:
+ .. seealso::
- :meth:`.Query.filter` - filter on SQL expressions.
+ :meth:`.Query.filter` - filter on SQL expressions.
"""
joined target, rather than starting back from the original
FROM clauses of the query.
- See also:
+ .. seealso::
:ref:`ormtutorial_joins` in the ORM tutorial.