I worte some code in Python for managing some database stuff. All I want to do, is to delete all parents of a 1-to-many relationsship , which should automatically delete all children. Here is my example code:
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship, Session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Parent(Base):
__tablename__ = 'parents'
id = Column(Integer, primary_key=True)
name = Column(String)
single_parent = True
children = relationship("Child", back_populates="parent", cascade="all, delete-orphan")
class Child(Base):
__tablename__ = 'children'
id = Column(Integer, primary_key=True)
name = Column(String)
parent_id = Column(Integer, ForeignKey('parents.id'))
parent = relationship('Parent', back_populates='children')
engine = create_engine("sqlite:///test.db", echo=True)
Base.metadata.create_all(bind=engine)
session = Session(engine)
# create data
parent1 = Parent(name='Parent 1', children=[Child(name='Child 1'), Child(name='Child 2')])
parent2 = Parent(name='Parent 2', children=[Child(name='Child 3'), Child(name='Child 4')])
session.add_all([parent1, parent2])
session.commit()
# Check
print("Before:")
print(session.query(Parent).all())
print(session.query(Child).all())
# Delete
session.query(Parent).delete()
session.commit()
When running, the parent elements will be deleted but none of the child elements. What am I doing wrong here? Thanks a lot for your help!
You need to modify
parent_iddeclaration:Replace:
With:
However, it's not sufficient when you use
SQLiteas database because Foreign Key Constraints are not enabled by default.You can enable Foreign Key Constraint with a(see @GordThompson's comment below)PRAGMAdirective at database level:Or you can handle this feature with `SQLAlchemy by listening for events:
Test:
Output: