Using the legacy ‘backref’ relationship parameter
The relationship.backref keyword should be considered legacy, and use of with explicit relationship() constructs should be preferred. Using individual constructs provides advantages including that both ORM mapped classes will include their attributes up front as the class is constructed, rather than as a deferred step, and configuration is more straightforward as all arguments are explicit. New PEP 484 features in SQLAlchemy 2.0 also take advantage of attributes being explicitly present in source code rather than using dynamic attribute generation.
See also
For general information about bidirectional relationships, see the following sections:
- in the SQLAlchemy Unified Tutorial, presents an overview of bi-directional relationship configuration and behaviors using
The keyword argument on the relationship() construct allows the automatic generation of a new that will be automatically be added to the ORM mapping for the related class. It will then be placed into a relationship.back_populates configuration against the current being configured, with both relationship() constructs referring to each other.
Starting with the following example:
The above configuration establishes a collection of objects on User
called User.addresses
. It also establishes a .user
attribute on which will refer to the parent User
object. Using it’s equivalent to the following:
Since generates a whole new relationship(), the generation process by default will attempt to include corresponding arguments in the new that correspond to the original arguments. As an example, below is a relationship() that includes a which also includes the relationship.backref keyword:
When the “backref” is generated, the condition is copied to the new relationship() as well:
Other arguments that are transferrable include the parameter that refers to a many-to-many association table, as well as the “join” arguments relationship.primaryjoin and ; “backref” is smart enough to know that these two arguments should also be “reversed” when generating the opposite side.
Specifying Backref Arguments
Lots of other arguments for a “backref” are not implicit, and include arguments like , relationship.remote_side, and relationship.cascade_backrefs. For this case we use the function in place of a string; this will store a specific set of arguments that will be transferred to the new relationship() when generated: