0

I'm using FastAPI with SQLAlchemy, Alembic, and SQLite3.

Here are my simplified models

class Parent(Base):
     __tablename__ = "parent"
      id = Column(Integer, primary_key=True, index=True)
      children = relationship(
        "Child", cascade="all, delete, delete-orphan", back_populates="parent"
      )   
  
class Child(Base):     
    __tablename__ = "child"
    id = Column(Integer, primary_key=True, index=True)
    parent_id = Column(Integer, ForeignKey("parent.id", ondelete="CASCADE"))
    parent = relationship("Parent", back_populates="children")

And Alembic generates the foreignkey constraint like this:

sa.ForeignKeyConstraint(['parent_id'], ['parent.id'], ondelete='CASCADE') 

Everything works just fine. I can create, delete, read parents and children, and children are attached to their parents through the foreign key. However when I'm deleting a parent it doesn't cascade, and the children stay in the database.

The foreign key ids don't turn into NULL, they stay their original number. If I create the parents again with that id, they're related again.

What could be the problem?

0 Answers0