Reputation: 722
I have two relations: Service and Stop. They form a many-to-many relationship with each other. I would like to clear all data from both tables while also emptying their many-to-many linking table.
I tried the following.
Service.query.delete()
Stop.query.delete()
This cleared both tables, however all data in the linking table remained untouched.
Service model:
class Service(Base):
__tablename__ = 'service'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
service_type = Column(String(250), nullable=False)
description = Column(String(250), nullable=False)
Stop model:
class Stop(Base):
__tablename__ = 'stop'
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
latitude = Column(Float(), nullable=False)
longitude = Column(Float(), nullable=False)
services = relationship("Service",
secondary=stop_service,
backref="stop")
Can someone please tell me how to automatically clear the linking table too, without having to loop through the "stop" table?
Upvotes: 2
Views: 491
Reputation: 160015
Just set ondelete
to CASCADE
in your joining table (stop_service
)'s definition:
stop_service = Table("stop_service", meta,
Column("service_id", ForeignKey('Service.id', ondelete="CASCADE")),
Column("stop_id", ForeignKey('Stop.id', ondelete="CASCADE")))
Upvotes: 2