SQLAlchemy: cascade delete

后端 未结 9 1570
星月不相逢
星月不相逢 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条回答
  •  情话喂你
    2020-11-28 01:44

    TLDR: If the above solutions don't work, try adding nullable=False to your column.

    I'd like to add a small point here for some people who may not get the cascade function to work with the existing solutions (which are great). The main difference between my work and the example was that I used automap. I do not know exactly how that might interfere with the setup of cascades, but I want to note that I used it. I am also working with a SQLite database.

    I tried every solution described here, but rows in my child table continued to have their foreign key set to null when the parent row was deleted. I'd tried all the solutions here to no avail. However, the cascade worked once I set the child column with the foreign key to nullable = False.

    On the child table, I added:

    Column('parent_id', Integer(), ForeignKey('parent.id', ondelete="CASCADE"), nullable=False)
    Child.parent = relationship("parent", backref=backref("children", passive_deletes=True)
    

    With this setup, the cascade functioned as expected.

提交回复
热议问题