python – Using the relationship () function in SQLAlchemy

Question:

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 () .

Answer:

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.name, 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.id'))

    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 = [
            Address(email_address='jack@gmail.com'),
            Address(email_address='j25@yahoo.com'),
            Address(email_address='jack@hotmail.com'),
            ]

Those. you operate with objects, not id's

Scroll to Top