SQLAlchemy: cascade delete

后端 未结 9 1553
星月不相逢
星月不相逢 2020-11-28 01:07

I must be missing something trivial with SQLAlchemy\'s cascade options because I cannot get a simple cascade delete to operate correctly -- if a parent element is a deleted,

9条回答
  •  -上瘾入骨i
    2020-11-28 01:34

    Steven's answer is solid. I'd like to point out an additional implication.

    By using relationship, you're making the app layer (Flask) responsible for referential integrity. That means other processes that access the database not through Flask, like a database utility or a person connecting to the database directly, will not experience those constraints and could change your data in a way that breaks the logical data model you worked so hard to design.

    Whenever possible, use the ForeignKey approach described by d512 and Alex. The DB engine is very good at truly enforcing constraints (in an unavoidable way), so this is by far the best strategy for maintaining data integrity. The only time you need to rely on an app to handle data integrity is when the database can't handle them, e.g. versions of SQLite that don't support foreign keys.

    If you need to create further linkage among entities to enable app behaviors like navigating parent-child object relationships, use backref in conjunction with ForeignKey.

提交回复
热议问题