Module 10 Exercises: Mastering the Data Layer

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.

  1. Create a Category model (e.g., "Electronics", "Books").
  2. Create a Product model.
  3. 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:

  1. Takes a Session (database) object as an argument.
  2. Uses a select statement to find all products where is_active is True.
  3. 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:

  1. Delete their Profile.
  2. Delete all their Posts.
  3. Set their status to "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.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn