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 expenseupdates.model_dump(exclude_unset=True)— converts theExpenseUpdateobject 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 loadedexpenseobject. 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.
- Inside
update_expense, replacepasswithexpense = session.get(Expense, expense_id). - Add an
if not expense:block. Inside it, raiseHTTPException(status_code=404, detail="Expense not found"). - 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. - Call
session.add(expense)to mark the updated expense as pending. - Call
session.commit()to write the changes to the database. - Call
session.refresh(expense)to reload the expense from the database. - Return
expense.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding