Filter by Date Range
Add start and end query parameters to GET /expenses using chained where conditions
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Chaining where conditions
You already use .where(Expense.category == category) to filter by category. Date range filtering adds two more conditions using the same pattern:
if start:
statement = statement.where(Expense.date >= start)
if end:
statement = statement.where(Expense.date <= end)Each .where() call narrows the results further. If the client sends ?start=2024-01-01&end=2024-03-31, both conditions apply. If they send only ?start=2024-01-01, only the start condition applies. If neither is sent, the query runs without date filtering.
String comparison works for dates stored in YYYY-MM-DD format because alphabetical order matches chronological order. "2024-06-15" >= "2024-01-01" is true — the same way it would be for dates as numbers. The validator you added in Course 1 ensures only valid YYYY-MM-DD dates are stored, so this comparison is safe.
The spending_summary endpoint
You may notice spending_summary now has a Python-loop implementation. That was added between lessons as a placeholder — the endpoint needs to return something while you finish the other improvements. You will replace it with a proper SQL aggregation query in the next chapter.
Instructions
Add start and end query parameters to list_expenses.
- Add
start: Optional[str] = Noneas a new parameter tolist_expenses, aftercategory. - Add
end: Optional[str] = Noneas a new parameter, afterstart. - After the
if category:block, add anif start:block. Inside it, reassignstatement = statement.where(Expense.date >= start). - After the
if start:block, add anif end:block. Inside it, reassignstatement = statement.where(Expense.date <= end).
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding