設定好資料庫的連線引擎後,今天我們要來定義資料庫裡面的「資料表」長什麼樣子。
在專案目錄下,我們新增一個 models.py 的檔案。我們要建立一個商品(Item)的資料庫模型,並讓它繼承昨天在 database.py 裡定義好的 Base:
from sqlalchemy import Column, Integer, String, Float
from database import Base
class Item(Base):
tablename = "items"
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
description = Column(String, nullable=True)
price = Column(Float)
在這段程式碼中:
tablename = "items" 代表這張表在資料庫裡真實的名稱。
id 定義為 Integer 並且是 primary_key(主鍵),資料庫會自動幫它遞增編號。
name、description 與 price 分別對應到字串與浮點數型態的欄位。
要特別注意的是,這裡的 SQLAlchemy 模型是用來跟「資料庫」溝通的,而前幾天寫的 Pydantic 模型是用來驗證「前端傳來的 API 資料」。這兩者分工合作,是 FastAPI 開發中非常經典的設計模式。