Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy: what is the difference between declaring the cascade within the foreign key vs relation?

Tags:

sqlalchemy

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!

like image 745
steve Avatar asked May 18 '10 02:05

steve


People also ask

What is Cascade in SQLAlchemy?

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.

What does relationship do in SQLAlchemy?

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.

What does Ondelete cascade mean?

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.

What is foreign key in SQLAlchemy?

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.


1 Answers

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.

like image 103
Ants Aasma Avatar answered Oct 18 '22 20:10

Ants Aasma