tags:

views:

31

answers:

1

what is the difference between declaring the cascade within a foreign key vs relations?

class Contact(Base):
    __tablename__ = 'contacts'
    id = Column(Integer, primary_key=True)
    addresses = relation("Address", backref="contact")

class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    contact_id = Column(Integer, ForeignKey('contact.id', onupdate="CASCADE", ondelete="CASCADE")))

vs

class Contact(Base):
    __tablename__ = 'contacts'
    id = Column(Integer, primary_key=True)
    addresses = relation("Address", backref="contact", cascade="all, delete-orphan")

class Address(Base):
    __tablename__ = 'addresses'
    id = Column(Integer, primary_key=True)
    contact_id = Column(Integer, ForeignKey('contact.id'))

with the foreign key declaration, it seems like the cascade is enforced at the database level. how does the relations approach work? thanks!

+1  A: 

You are correct that the foreign key cascade is done on the database level. Perhaps unsurprisingly the relationship approach is done on the Python level. When the delete of the parent is flushed from the session SQLAlchemy reads in the relation and issues delete to all members, processing any other cascades.

Also note that if you use the database cascade, you'll need to also configure the relationship to be aware of the fact.

Ants Aasma
So I should really combine the two so that the relationship is aware of the database cascade?
steve
See the documentation for passive_updates and passive_deletes parameters for the relationship function: http://www.sqlalchemy.org/docs/reference/orm/mapping.html#sqlalchemy.orm.relationship
Ants Aasma
awesome. thanks for the clarification.
steve