开发者

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

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 = relat开发者_开发知识库ion("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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜