CRUD 的最後一塊拼圖就是更新 (Update) 與刪除 (Delete) 了。這兩個動作有一個共同的前提:你必須先確認「資料是否存在」,因此我們會結合昨天學到的查詢技巧和 HTTPException。
首先是更新資料,我們使用 PUT 方法:
@app.put("/items/{item_id}")
def update_item(item_id: int, update_data: ItemCreate, db: Session = Depends(get_db)):
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="找不到要更新的商品")
item.name = update_data.name
item.price = update_data.price
item.description = update_data.description
db.commit()
db.refresh(item)
return item
你會發現更新其實很直覺,就是把查詢出來的物件屬性改掉,然後直接 db.commit() 就可以了,SQLAlchemy 會聰明地幫你轉成 UPDATE 的 SQL 語法。
最後是刪除資料,使用 DELETE 方法:
@app.delete("/items/{item_id}")
def delete_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="找不到要刪除的商品")
db.delete(item)
db.commit()
return {"message": f"商品 ID {item_id} 已成功刪除"}
到這裡,我們用短短三天的時間,就把最基礎、但也最核心的資料庫 CRUD 完整走過一遍了。你的 FastAPI 專案現在已經具備了完整的資料持久化與操作能力,接下來就可以繼續往更進階的架構優化邁進!