Rewrite Delete Expense
Replace dict.pop with session.delete and session.commit
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Deleting a record
Deleting from a database follows the same lookup-then-act pattern as get:
expense = session.get(Expense, expense_id)
if not expense:
raise HTTPException(status_code=404, detail="Expense not found")
session.delete(expense)
session.commit()
return expenseNotice that you return expense after deleting it. You loaded the object before the delete, so you still have it in memory and can include it in the response. The old code did the same thing — expenses.pop(expense_id) removed the item from the dict and returned its value in one step. Here you do it in two steps, but the result is the same.
session.commit() is required after session.delete(). Without it, the delete is pending but never written to the database.
Instructions
Rewrite the delete_expense endpoint.
- Inside
delete_expense, replacepasswithexpense = session.get(Expense, expense_id). - Add an
if not expense:block. Inside it, raiseHTTPException(status_code=404, detail="Expense not found"). - Call
session.delete(expense). - Call
session.commit(). - Return
expense.
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding