Rewrite Update Expense
Exit

Rewrite Update Expense

Replace dict.update with sqlmodel_update, session.add, session.commit, and session.refresh

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Applying partial updates

The PATCH /expenses/{id} endpoint applies only the fields the client sent — leaving the rest unchanged. The old code used dict.update(). The new code uses sqlmodel_update():

expense = session.get(Expense, expense_id)
if not expense:
    raise HTTPException(status_code=404, detail="Expense not found")
expense.sqlmodel_update(updates.model_dump(exclude_unset=True))
session.add(expense)
session.commit()
session.refresh(expense)
return expense

  • updates.model_dump(exclude_unset=True) — converts the ExpenseUpdate object to a dict containing only the fields the client actually sent. If the client sent {"amount": 15.00}, this returns {"amount": 15.00} — not {"amount": 15.00, "description": None, "category": None}.
  • expense.sqlmodel_update(...) — applies that dict to the loaded expense object. Fields not in the dict are left unchanged.
  • session.add(expense) — marks the updated object as pending in the session.
  • session.commit() — writes the changes to the database.
  • session.refresh(expense) — reloads the object from the database to confirm the final state.

This is the most involved rewrite of the lesson, but the pattern — load, check, update, commit, refresh, return — is consistent with every other endpoint.

Instructions

Rewrite the update_expense endpoint.

  1. Inside update_expense, replace pass with expense = session.get(Expense, expense_id).
  2. Add an if not expense: block. Inside it, raise HTTPException(status_code=404, detail="Expense not found").
  3. Call expense.sqlmodel_update(updates.model_dump(exclude_unset=True)). This applies only the fields the client sent, leaving the rest of the expense unchanged.
  4. Call session.add(expense) to mark the updated expense as pending.
  5. Call session.commit() to write the changes to the database.
  6. Call session.refresh(expense) to reload the expense from the database.
  7. Return expense.