Filter by Date Range
Exit

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.

  1. Add start: Optional[str] = None as a new parameter to list_expenses, after category.
  2. Add end: Optional[str] = None as a new parameter, after start.
  3. After the if category: block, add an if start: block. Inside it, reassign statement = statement.where(Expense.date >= start).
  4. After the if start: block, add an if end: block. Inside it, reassign statement = statement.where(Expense.date <= end).