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!
Mappers support the concept of configurable cascade behavior on relationship() constructs. This refers to how operations performed on a “parent” object relative to a particular Session should be propagated to items referred to by that relationship (e.g. “child” objects), and is affected by the relationship.
The relationship function is a part of Relationship API of SQLAlchemy ORM package. It provides a relationship between two mapped classes. This corresponds to a parent-child or associative table relationship.
Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
A foreign key in SQL is a table-level construct that constrains one or more columns in that table to only allow values that are present in a different set of columns, typically but not always located on a different table.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With