Rewrite List Expenses
Replace the Python filter loop with a database query using select and where
💻
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Building a query with select
The old list_expenses filtered expenses in Python by looping through the dict. The new version builds a SQL query and lets the database do the filtering:
statement = select(Expense)
if category:
statement = statement.where(Expense.category == category)
return session.exec(statement).all()select(Expense)— creates a query that selects all columns from theexpensetable. Think of it asSELECT * FROM expense..where(Expense.category == category)— adds a filter condition. SQLModel translatesExpense.category == categoryinto a SQLWHEREclause. You chain.where()calls to add more conditions — you will use this in Lesson 3 for date range filtering.session.exec(statement).all()— sends the query to the database and returns all matching rows as a list.
If no category is provided, the if block is skipped and all expenses are returned. The filtering happens inside the database, not in a Python loop.
Instructions
Rewrite the list_expenses endpoint.
- Add
selectto the import fromsqlmodel— add it to the existing import line that already hasSession. - Inside
list_expenses, replacepasswith astatement = select(Expense)line. - Add an
if category:block. Inside it, reassignstatement = statement.where(Expense.category == category). - Return
session.exec(statement).all().
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding