python – Using the relationship () function in SQLAlchemy


Explain why in SQLAlchemy use the relationship () function when creating object classes associated with database tables, if foreign keys can be specified when creating table classes using the ForeignKey () function when defining a column? Or does relationship () make sense when using a declarative model, where a single class is defined for the table and its associated object?

Provide examples showing how a class is used that has fields defined via relationship () .


Example from the author pycon2013 zzzeek

Create two tables User and Address .

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    fullname = Column(String)

    def __repr__(self):
        return "<User(%r, %r)>" % (
      , self.fullname

class Address(Base):
    __tablename__ = 'address'

    id = Column(Integer, primary_key=True)
    email_address = Column(String, nullable=False)
    user_id = Column(Integer, ForeignKey(''))

    user = relationship("User", backref="addresses")

Using my_address_obj.user we get the OBJECT of the user, and my_user_obj.addresses will return a list of OBJECTS of all addresses referring to User . In this way, a relationship links objects rather than simply returning an id value.

An example from the presentation:

# Пока у пользователя нет "addresses"
jack = User(name='jack', fullname='Jack Bean')
jack.addresses  # Пустой список

# Добавим адресов ему
jack.addresses = [

Those. you operate with objects, not id's

Scroll to Top