Search Descriptions
Add a search query parameter to GET /expenses using contains
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Searching inside text
The last query addition lets clients find expenses by keyword. A search for "coffee" should return any expense whose description contains that word, regardless of case or position.
SQLModel's .contains() method maps to a SQL LIKE query:
if search:
statement = statement.where(Expense.description.contains(search))Expense.description.contains(search) generates WHERE description LIKE '%coffee%'. The % wildcards match any characters before or after the search term. SQLite's LIKE is case-insensitive for ASCII characters by default, so searching for "coffee" also matches "Coffee" or "COFFEE".
This chains with the existing conditions — you can combine ?category=food&search=coffee to find food expenses that mention coffee in the description.
Instructions
Add a search query parameter to list_expenses.
- Add
search: Optional[str] = Noneas a new parameter tolist_expenses, afterend. - After the
if end:block, add anif search:block. Inside it, reassignstatement = statement.where(Expense.description.contains(search)).
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding