Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')
like image 444
Peter Sampras Avatar asked Nov 03 '13 18:11

Peter Sampras


1 Answers

Use cascades:

    show = db.relationship('Show',
                           backref=db.backref('episodes', cascade="all, delete-orphan"),
                           lazy='joined')
like image 187
javex Avatar answered Sep 23 '22 22:09

javex