SQLAlchemy cascade

On my brain storming project, I learned more about working with databases and database design. Foreign keys with cascade delete refer to when a parent row has dependent children. Dependent children have foreign keys that refer back to the parent’s primary key. When a parent row with dependent children is deleted, the children row are deleted as well. You can set the foreign key to NULL on delete as well.

In SQLAlchemy, this is implemented by using relationships. Below is a portion of my models.py file. The User table is parent to IdeaSessions. Each IdeaSession has a creator_id which references a user id. On the User table, a relationship is defined and the cascade attribute is set to ‘delete’.

from app import db

class User(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    auth_server_id = db.Column(db.String, default=None)
    created = db.Column(
        db.DateTime, default=datetime.utcnow, nullable=False
    name = db.Column(db.String, nullable=False)
    email = db.Column(db.String, nullable=False)
    profile_pic = db.Column(db.String, nullable=False)
    idea_session = db.relationship("IdeaSession", cascade='delete')
    ideas = db.relationship("Idea", cascade='delete')
    scores = db.relationship("Score", cascade='delete')
    permissions = db.relationship("Permission", cascade='delete')

class IdeaSession(db.Model):
    id = db.Column(db.Integer, nullable=False, primary_key=True)
    name = db.Column(db.String, nullable=False)
    description = db.Column(db.String, default='No Description')
    created = db.Column(db.DateTime, default=datetime.utcnow)
    creator_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    idea = db.relationship("Idea", cascade='delete')
    permissions = db.relationship("Permission", cascade='delete')

    def json_view(self):
        return {"id": self.id, "name": self.name, "created": self.created, "creator": self.creator_id}