
Module 10 Exercises: Mastering the Data Layer
Practical exercises to consolidate your knowledge of SQLModel, relationships, and database transactions.
Module 10 Exercises: Mastering the Data Layer
persistent data is the lifeblood of your application. These exercises will help you bridge the gap between volatile code and durable storage.
Exercise 1: The One-to-Many Connection
You are building an Online Store API.
- Create a
Categorymodel (e.g., "Electronics", "Books"). - Create a
Productmodel. - Establish a relationship where one category can own many products. Use SQLModel and
Relationship.
Exercise 2: Implementing a CRUD Function
Write a Python function called get_active_products that:
- Takes a
Session(database) object as an argument. - Uses a
selectstatement to find all products whereis_activeisTrue. - Returns the list of results.
Exercise 3: The Transaction Logic
You are building a Social Media App. When a user deletes their account, you must:
- Delete their
Profile. - Delete all their
Posts. - Set their
statusto "inactive" in a global log.
Describe how you would use a Session Transaction to ensure that either all three actions happen, or none of them do.
Self-Correction / Discussion
Exercise 1 Answer:
class Category(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
products: List["Product"] = Relationship(back_populates="category")
class Product(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str
category_id: int = Field(foreign_key="category.id")
category: Category = Relationship(back_populates="products")
Exercise 2 Answer:
from sqlmodel import select
def get_active_products(db: Session):
statement = select(Product).where(Product.is_active == True)
results = db.exec(statement)
return results.all()
Exercise 3 Answer:
You would wrap the logic in a with Session(engine) as session: block. Perform all three operations (session.delete(profile), session.delete(posts), session.add(log)), and then call session.commit(). If an error happens during any step, call session.rollback().
Summary of Module 10
You have mastered the most complex layer of any API.
- SQLModel: You can bridge Python and SQL.
- Relationships: You can model complex, linked data.
- Lifecycle: You can operate a production database at scale.
In Module 11: Background Tasks and Async Work, we will learn how to handle long-running tasks without making your users wait for a response.