Open In App

SQLAlchemy Cascading Deletes

SQLAlchemy is a powerful ORM (Object-Relational Mapping) library for Python that allows developers to interact with relational databases using Python objects. It provides a rich set of tools for querying, updating, and manipulating data, making it a popular choice for building web applications and other software that requires working with databases.

One of the most useful features of SQLAlchemy is its support for cascading deletes. This feature allows you to automatically delete related records in a database when you delete a record that has dependencies. In this article, we will discuss SQLAlchemy cascading deletes in more detail and provide examples to help you better understand how it works.
Explanation:



For this article, we will be using a simple database with two tables: “users” and “posts“. Each post belongs to a user, and each user can have multiple posts. The database schema is shown below:
 

Users

Posts



The “posts” table has a foreign key constraint that references the “users” table. The ON DELETE CASCADE option specifies that when a user is deleted, all of their posts should also be deleted.

To perform SQLAlchemy Cascading Deletes on the tables created in the above code, we can use the following Python code:

Don’t forget to update the code with your password and database name respectively
 




from sqlalchemy import create_engine, ForeignKey, Column, Integer, String, Text
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
  
# Create the engine and session
engine = create_engine(
    'mysql+mysqlconnector://root:<your password>@localhost/<your database name>')
Session = sessionmaker(bind=engine)
session = Session()
  
# Define the models
Base = declarative_base()
  
  
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), nullable=False)
    posts = relationship('Post', backref='user', cascade='all, delete')
  
  
class Post(Base):
    __tablename__ = 'posts'
    id = Column(Integer, primary_key=True)
    title = Column(String(100), nullable=False)
    body = Column(Text, nullable=False)
    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
  
  
# Delete a user and all of their posts
user = session.query(User).filter_by(name='John').first()
session.delete(user)
session.commit()
  
# Check if the user and their posts have been deleted
user = session.query(User).filter_by(name='John').first()
print(user)  # This should be None
posts = session.query(Post).filter_by(user_id=1).all()
print(posts)  # This should be an empty list

Updated Table after performing SQLAlchemy Cascading:

Output Image after executing code


Article Tags :