Basic Relationship Patterns

A quick walkthrough of the basic relational patterns.

The imports used for each of the following sections is as follows:

  1. from sqlalchemy import Table, Column, Integer, ForeignKey
  2. from sqlalchemy.orm import relationship
  3. from sqlalchemy.ext.declarative import declarative_base
  4. Base = declarative_base()

One To Many

A one to many relationship places a foreign key on the child table referencing the parent. relationship() is then specified on the parent, as referencing a collection of items represented by the child:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. id = Column(Integer, primary_key=True)
  4. children = relationship("Child")
  5. class Child(Base):
  6. __tablename__ = 'child'
  7. id = Column(Integer, primary_key=True)
  8. 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 an additional relationship() and connect the two using the relationship.back_populates parameter:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. id = Column(Integer, primary_key=True)
  4. children = relationship("Child", back_populates="parent")
  5. class Child(Base):
  6. __tablename__ = 'child'
  7. id = Column(Integer, primary_key=True)
  8. parent_id = Column(Integer, ForeignKey('parent.id'))
  9. parent = relationship("Parent", back_populates="children")

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

Alternatively, the relationship.backref option may be used on a single relationship() instead of using relationship.back_populates:

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

Configuring Delete Behavior for One to Many

It is often the case that all Child objects should be deleted when their owning Parent is deleted. To configure this behavior, the delete cascade option described at delete is used. An additional option is that a Child object can itself be deleted when it is deassociated from its parent. This behavior is described at delete-orphan.

See also

delete

Using foreign key ON DELETE cascade with ORM relationships

delete-orphan

Many To One

Many to one places a foreign key in the parent table referencing the child. relationship() is declared on the parent, where a new scalar-holding attribute will be created:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. id = Column(Integer, primary_key=True)
  4. child_id = Column(Integer, ForeignKey('child.id'))
  5. child = relationship("Child")
  6. class Child(Base):
  7. __tablename__ = 'child'
  8. id = Column(Integer, primary_key=True)

Bidirectional behavior is achieved by adding a second relationship() and applying the relationship.back_populates parameter in both directions:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. id = Column(Integer, primary_key=True)
  4. child_id = Column(Integer, ForeignKey('child.id'))
  5. child = relationship("Child", back_populates="parents")
  6. class Child(Base):
  7. __tablename__ = 'child'
  8. id = Column(Integer, primary_key=True)
  9. parents = relationship("Parent", back_populates="child")

Alternatively, the relationship.backref parameter may be applied to a single relationship(), such as Parent.child:

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

One To One

One To One is essentially a bidirectional relationship with a scalar attribute on both sides. To achieve this, the 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:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. id = Column(Integer, primary_key=True)
  4. child = relationship("Child", uselist=False, back_populates="parent")
  5. class Child(Base):
  6. __tablename__ = 'child'
  7. id = Column(Integer, primary_key=True)
  8. parent_id = Column(Integer, ForeignKey('parent.id'))
  9. parent = relationship("Parent", back_populates="child")

Or for many-to-one:

  1. class Parent(Base):
  2. __tablename__ = 'parent'
  3. id = Column(Integer, primary_key=True)
  4. child_id = Column(Integer, ForeignKey('child.id'))
  5. child = relationship("Child", back_populates="parent")
  6. class Child(Base):
  7. __tablename__ = 'child'
  8. id = Column(Integer, primary_key=True)
  9. parent = relationship("Parent", back_populates="child", uselist=False)

As always, the relationship.backref and backref() functions may be used in lieu of the relationship.back_populates approach; to specify uselist on a backref, use the backref() function:

  1. from sqlalchemy.orm import backref
  2. class Parent(Base):
  3. __tablename__ = 'parent'
  4. id = Column(Integer, primary_key=True)
  5. child_id = Column(Integer, ForeignKey('child.id'))
  6. child = relationship("Child", backref=backref("parent", uselist=False))

Many To Many

Many to Many adds an association table between two classes. The association table is indicated by the relationship.secondary argument to relationship(). Usually, the Table uses the MetaData object associated with the declarative base class, so that the ForeignKey directives can locate the remote tables with which to link:

  1. association_table = Table('association', Base.metadata,
  2. Column('left_id', Integer, ForeignKey('left.id')),
  3. Column('right_id', Integer, ForeignKey('right.id'))
  4. )
  5. class Parent(Base):
  6. __tablename__ = 'left'
  7. id = Column(Integer, primary_key=True)
  8. children = relationship("Child",
  9. secondary=association_table)
  10. class Child(Base):
  11. __tablename__ = 'right'
  12. id = Column(Integer, primary_key=True)

For a bidirectional relationship, both sides of the relationship contain a collection. Specify using relationship.back_populates, and for each relationship() specify the common association table:

  1. association_table = Table('association', Base.metadata,
  2. Column('left_id', Integer, ForeignKey('left.id')),
  3. Column('right_id', Integer, ForeignKey('right.id'))
  4. )
  5. class Parent(Base):
  6. __tablename__ = 'left'
  7. id = Column(Integer, primary_key=True)
  8. children = relationship(
  9. "Child",
  10. secondary=association_table,
  11. back_populates="parents")
  12. class Child(Base):
  13. __tablename__ = 'right'
  14. id = Column(Integer, primary_key=True)
  15. parents = relationship(
  16. "Parent",
  17. secondary=association_table,
  18. back_populates="children")

When using the relationship.backref parameter instead of relationship.back_populates, the backref will automatically use the same relationship.secondary argument for the reverse relationship:

  1. association_table = Table('association', Base.metadata,
  2. Column('left_id', Integer, ForeignKey('left.id')),
  3. Column('right_id', Integer, ForeignKey('right.id'))
  4. )
  5. class Parent(Base):
  6. __tablename__ = 'left'
  7. id = Column(Integer, primary_key=True)
  8. children = relationship("Child",
  9. secondary=association_table,
  10. backref="parents")
  11. class Child(Base):
  12. __tablename__ = 'right'
  13. id = Column(Integer, primary_key=True)

The relationship.secondary argument of 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 is complete:

  1. class Parent(Base):
  2. __tablename__ = 'left'
  3. id = Column(Integer, primary_key=True)
  4. children = relationship("Child",
  5. secondary=lambda: association_table,
  6. backref="parents")

With the declarative extension in use, the traditional “string name of the table” is accepted as well, matching the name of the table as stored in Base.metadata.tables:

  1. class Parent(Base):
  2. __tablename__ = 'left'
  3. id = Column(Integer, primary_key=True)
  4. children = relationship("Child",
  5. secondary="association",
  6. backref="parents")

Warning

When passed as a Python-evaluable string, the relationship.secondary argument is interpreted using Python’s eval() function. DO NOT PASS UNTRUSTED INPUT TO THIS STRING. See Evaluation of relationship arguments for details on declarative evaluation of relationship() arguments.

Deleting Rows from the Many to Many Table

A behavior which is unique to the relationship.secondary argument to relationship() is that the 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 record from the collection will have the effect of the row being deleted on flush:

  1. # row will be deleted from the "secondary" table
  2. # automatically
  3. myparent.children.remove(somechild)

A question which often arises is how the row in the “secondary” table can be deleted when the child object is handed directly to Session.delete():

  1. session.delete(somechild)

There are several possibilities here:

  • If there is a relationship() from Parent to Child, but there is not a reverse-relationship that links a particular Child to each Parent, SQLAlchemy will not have any awareness that when deleting this particular Child object, it needs to maintain the “secondary” table that links it to the Parent. No delete of the “secondary” table will occur.

  • If there is a relationship that links a particular Child to each Parent, suppose it’s called Child.parents, SQLAlchemy by default will load in the Child.parents collection to locate all Parent objects, and remove each row from the “secondary” table which establishes this link. Note that this relationship does not need to be bidirectional; SQLAlchemy is strictly looking at every relationship() associated with the Child object being deleted.

  • A higher performing option here is to use ON DELETE CASCADE directives with the foreign keys used by the database. Assuming the database supports this feature, the database itself can be made to automatically delete rows in the “secondary” table as referencing rows in “child” are deleted. SQLAlchemy can be instructed to forego actively loading in the Child.parents collection in this case using the relationship.passive_deletes directive on relationship(); see Using foreign key ON DELETE cascade with ORM relationships for more details on this.

Note again, these behaviors are only relevant to the relationship.secondary option used with relationship(). If dealing with association tables that are mapped explicitly and are not present in the relationship.secondary option of a relevant relationship(), cascade rules can be used instead to automatically delete entities in reaction to a related entity being deleted - see Cascades for information on this feature.

See also

Using delete cascade with many-to-many relationships

Using foreign key ON DELETE with many-to-many relationships

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

  1. class Association(Base):
  2. __tablename__ = 'association'
  3. left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
  4. right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
  5. extra_data = Column(String(50))
  6. child = relationship("Child")
  7. class Parent(Base):
  8. __tablename__ = 'left'
  9. id = Column(Integer, primary_key=True)
  10. children = relationship("Association")
  11. class Child(Base):
  12. __tablename__ = 'right'
  13. id = Column(Integer, primary_key=True)

As always, the bidirectional version makes use of relationship.back_populates or relationship.backref:

  1. class Association(Base):
  2. __tablename__ = 'association'
  3. left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
  4. right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
  5. extra_data = Column(String(50))
  6. child = relationship("Child", back_populates="parents")
  7. parent = relationship("Parent", back_populates="children")
  8. class Parent(Base):
  9. __tablename__ = 'left'
  10. id = Column(Integer, primary_key=True)
  11. children = relationship("Association", back_populates="parent")
  12. class Child(Base):
  13. __tablename__ = 'right'
  14. id = Column(Integer, primary_key=True)
  15. parents = relationship("Association", back_populates="child")

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:

  1. # create parent, append a child via association
  2. p = Parent()
  3. a = Association(extra_data="some data")
  4. a.child = Child()
  5. p.children.append(a)
  6. # iterate through child objects via association, including association
  7. # attributes
  8. for assoc in p.children:
  9. print(assoc.extra_data)
  10. 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.

Warning

The association object pattern does not coordinate changes with a separate relationship that maps the association table as “secondary”.

Below, changes made to Parent.children will not be coordinated with changes made to Parent.child_associations or Child.parent_associations in Python; while all of these relationships will continue to function normally by themselves, changes on one will not show up in another until the Session is expired, which normally occurs automatically after Session.commit():

  1. class Association(Base):
  2. __tablename__ = 'association'
  3. left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
  4. right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
  5. extra_data = Column(String(50))
  6. child = relationship("Child", backref="parent_associations")
  7. parent = relationship("Parent", backref="child_associations")
  8. class Parent(Base):
  9. __tablename__ = 'left'
  10. id = Column(Integer, primary_key=True)
  11. children = relationship("Child", secondary="association")
  12. class Child(Base):
  13. __tablename__ = 'right'
  14. id = Column(Integer, primary_key=True)

Additionally, just as changes to one relationship aren’t reflected in the others automatically, writing the same data to both relationships will cause conflicting INSERT or DELETE statements as well, such as below where we establish the same relationship between a Parent and Child object twice:

  1. p1 = Parent()
  2. c1 = Child()
  3. p1.children.append(c1)
  4. # redundant, will cause a duplicate INSERT on Association
  5. p1.child_associations.append(Association(child=c1))

It’s fine to use a mapping like the above if you know what you’re doing, though it may be a good idea to apply the viewonly=True parameter to the “secondary” relationship to avoid the issue of redundant changes being logged. However, to get a foolproof pattern that allows a simple two-object Parent->Child relationship while still using the association object pattern, use the association proxy extension as documented at Association Proxy.

Late-Evaluation of Relationship Arguments

Many of the examples in the preceding sections illustrate mappings where the various relationship() constructs refer to their target classes using a string name, rather than the class itself:

  1. class Parent(Base):
  2. # ...
  3. children = relationship("Child", back_populates="parent")
  4. class Child(Base):
  5. # ...
  6. parent = relationship("Parent", back_populates="children")

These string names are resolved into classes in the mapper resolution stage, which is an internal process that occurs typically after all mappings have been defined and is normally triggered by the first usage of the mappings themselves. The registry object is the container in which these names are stored and resolved to the mapped classes they refer towards.

In addition to the main class argument for relationship(), other arguments which depend upon the columns present on an as-yet undefined class may also be specified either as Python functions, or more commonly as strings. For most of these arguments except that of the main argument, string inputs are evaluated as Python expressions using Python’s built-in eval() function, as they are intended to recieve complete SQL expressions.

Warning

As the Python eval() function is used to interpret the late-evaluated string arguments passed to relationship() mapper configuration construct, these arguments should not be repurposed such that they would receive untrusted user input; eval() is not secure against untrusted user input.

The full namespace available within this evaluation includes all classes mapped for this declarative base, as well as the contents of the sqlalchemy package, including expression functions like desc() and sqlalchemy.sql.functions.func:

  1. class Parent(Base):
  2. # ...
  3. children = relationship(
  4. "Child",
  5. order_by="desc(Child.email_address)",
  6. primaryjoin="Parent.id == Child.parent_id"
  7. )

For the case where more than one module contains a class of the same name, string class names can also be specified as module-qualified paths within any of these string expressions:

  1. class Parent(Base):
  2. # ...
  3. children = relationship(
  4. "myapp.mymodel.Child",
  5. order_by="desc(myapp.mymodel.Child.email_address)",
  6. primaryjoin="myapp.mymodel.Parent.id == myapp.mymodel.Child.parent_id"
  7. )

The qualified path can be any partial path that removes ambiguity between the names. For example, to disambiguate between myapp.model1.Child and myapp.model2.Child, we can specify model1.Child or model2.Child:

  1. class Parent(Base):
  2. # ...
  3. children = relationship(
  4. "model1.Child",
  5. order_by="desc(mymodel1.Child.email_address)",
  6. primaryjoin="Parent.id == model1.Child.parent_id"
  7. )

The relationship() construct also accepts Python functions or lambdas as input for these arguments. This has the advantage of providing more compile-time safety and better support for IDEs and PEP 484 scenarios.

A Python functional approach might look like the following:

  1. from sqlalchemy import desc
  2. def _resolve_child_model():
  3. from myapplication import Child
  4. return Child
  5. class Parent(Base):
  6. # ...
  7. children = relationship(
  8. _resolve_child_model(),
  9. order_by=lambda: desc(_resolve_child_model().email_address),
  10. primaryjoin=lambda: Parent.id == _resolve_child_model().parent_id
  11. )

The full list of parameters which accept Python functions/lambdas or strings that will be passed to eval() are:

Changed in version 1.3.16: Prior to SQLAlchemy 1.3.16, the main relationship.argument to relationship() was also evaluated throught eval() As of 1.3.16 the string name is resolved from the class resolver directly without supporting custom Python expressions.

Warning

As stated previously, the above parameters to relationship() are evaluated as Python code expressions using eval(). DO NOT PASS UNTRUSTED INPUT TO THESE ARGUMENTS.

It should also be noted that in a similar way as described at Adding New Columns, any MapperProperty construct can be added to a declarative base mapping at any time. If we wanted to implement this relationship() after the Address class were available, we could also apply it afterwards:

  1. # first, module A, where Child has not been created yet,
  2. # we create a Parent class which knows nothing about Child
  3. class Parent(Base):
  4. # ...
  5. #... later, in Module B, which is imported after module A:
  6. class Child(Base):
  7. # ...
  8. from module_a import Parent
  9. # assign the User.addresses relationship as a class variable. The
  10. # declarative base class will intercept this and map the relationship.
  11. Parent.children = relationship(
  12. Child,
  13. primaryjoin=Child.parent_id==Parent.id
  14. )

Note

assignment of mapped properties to a declaratively mapped class will only function correctly if the “declarative base” class is used, which also provides for a metaclass-driven __setattr__() method which will intercept these operations. It will not work if the declarative decorator provided by registry.mapped() is used, nor will it work for an imperatively mapped class mapped by registry.map_imperatively().

Late-Evaluation for a many-to-many relationship

Many-to-many relationships include a reference to an additional, typically non-mapped Table object that is typically present in the MetaData collection referred towards by the registry. The late-evaluation system also includes support for having this attribute be specified as a string argument which will be resolved from this MetaData collection. Below we specify an association table keyword_author, sharing the MetaData collection associated with our declarative base and its registry. We can then refer to this Table by name in the relationship.secondary parameter:

  1. keyword_author = Table(
  2. 'keyword_author', Base.metadata,
  3. Column('author_id', Integer, ForeignKey('authors.id')),
  4. Column('keyword_id', Integer, ForeignKey('keywords.id'))
  5. )
  6. class Author(Base):
  7. __tablename__ = 'authors'
  8. id = Column(Integer, primary_key=True)
  9. keywords = relationship("Keyword", secondary="keyword_author")

For additional detail on many-to-many relationships see the section Many To Many.