Peter Sampras
Peter Sampras

Reputation: 445

SQLAlchemy relationship cascade deletion

I have read the documentation, but I still can't seem to understand exactly how to configure my models properly. It's a very simple TV show database and I want to configure it so that an Episode must have a corresponding Show parent instance to exist in the database. Whenever a Show is deleted, I want all of its episodes to be cascade deleted.

TL;DR: show.delete() --> all episodes ep where ep.show_id == show.id are deleted

How do I accomplish this?

class Show(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(128), nullable=False)

class Episode(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(256), nullable=False)

    # relationships
    show_id = db.Column(db.Integer, db.ForeignKey('show.id'), nullable=False)
    show = db.relationship('Show',
                           backref=db.backref('episodes'),
                           lazy='joined')

Upvotes: 7

Views: 9809

Answers (1)

javex
javex

Reputation: 7544

Use cascades:

    show = db.relationship('Show',
                           backref=db.backref('episodes', cascade="all, delete-orphan"),
                           lazy='joined')

Upvotes: 8

Related Questions