Configuring Relationships

See also

This section describes specifics about how the Declarative systeminteracts with SQLAlchemy ORM relationship constructs. For generalinformation about setting up relationships between mappings,see Object Relational Tutorial and Basic Relationship Patterns.

Relationships to other classes are done in the usual way, with the addedfeature that the class specified to relationship()may be a string name. The “class registry” associated with Baseis used at mapper compilation time to resolve the name into the actualclass object, which is expected to have been defined once the mapperconfiguration is used:

  1. class User(Base):
  2. __tablename__ = 'users'
  3.  
  4. id = Column(Integer, primary_key=True)
  5. name = Column(String(50))
  6. addresses = relationship("Address", backref="user")
  7.  
  8. class Address(Base):
  9. __tablename__ = 'addresses'
  10.  
  11. id = Column(Integer, primary_key=True)
  12. email = Column(String(50))
  13. user_id = Column(Integer, ForeignKey('users.id'))

Column constructs, since they are just that, are immediately usable,as below where we define a primary join condition on the Addressclass using them:

  1. class Address(Base):
  2. __tablename__ = 'addresses'
  3.  
  4. id = Column(Integer, primary_key=True)
  5. email = Column(String(50))
  6. user_id = Column(Integer, ForeignKey('users.id'))
  7. user = relationship(User, primaryjoin=user_id == User.id)

In addition to the main argument for relationship(),other arguments which depend upon the columns present on an as-yetundefined class may also be specified as strings. These strings areevaluated as Python expressions. The full namespace available withinthis evaluation includes all classes mapped for this declarative base,as well as the contents of the sqlalchemy package, includingexpression functions like desc() andfunc:

  1. class User(Base):
  2. # ....
  3. addresses = relationship("Address",
  4. order_by="desc(Address.email)",
  5. primaryjoin="Address.user_id==User.id")

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 pathswithin any of these string expressions:

  1. class User(Base):
  2. # ....
  3. addresses = relationship("myapp.model.address.Address",
  4. order_by="desc(myapp.model.address.Address.email)",
  5. primaryjoin="myapp.model.address.Address.user_id=="
  6. "myapp.model.user.User.id")

The qualified path can be any partial path that removes ambiguity betweenthe names. For example, to disambiguate betweenmyapp.model.address.Address and myapp.model.lookup.Address,we can specify address.Address or lookup.Address:

  1. class User(Base):
  2. # ....
  3. addresses = relationship("address.Address",
  4. order_by="desc(address.Address.email)",
  5. primaryjoin="address.Address.user_id=="
  6. "User.id")

Two alternatives also exist to using string-based attributes. A lambdacan also be used, which will be evaluated after all mappers have beenconfigured:

  1. class User(Base):
  2. # ...
  3. addresses = relationship(lambda: Address,
  4. order_by=lambda: desc(Address.email),
  5. primaryjoin=lambda: Address.user_id==User.id)

Or, the relationship can be added to the class explicitly after the classesare available:

  1. User.addresses = relationship(Address,
  2. primaryjoin=Address.user_id==User.id)

Configuring Many-to-Many Relationships

Many-to-many relationships are also declared in the same waywith declarative as with traditional mappings. Thesecondary argument torelationship() is as usual passed aTable object, which is typically declared in thetraditional way. The Table usually sharesthe MetaData object used by the declarative base:

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

Like other relationship() arguments, a string is acceptedas well, passing the string name of the table as defined in theBase.metadata.tables collection:

  1. class Author(Base):
  2. __tablename__ = 'authors'
  3. id = Column(Integer, primary_key=True)
  4. keywords = relationship("Keyword", secondary="keywords")

As with traditional mapping, its generally not a good idea to usea Table as the “secondary” argument which is also mapped toa class, unless the relationship() is declared with viewonly=True.Otherwise, the unit-of-work system may attempt duplicate INSERT andDELETE statements against the underlying table.