動かざることバグの如し

近づきたいよ 君の理想に

fastapiのmodels.pyとschema.pyのモデルの違い

環境

  • fastapi v0.75

モデルが2つある?

fastapiやってると、多くのチュートリアルでmodels.py、schema.pyが出てくる。

が、その違いがいまいち分からず混乱したのでメモ

models.pyはSQLAlchemy用、schema.pyはPydantic用ファイル

実際のソースコードでは何を継承しているかを見るとわかりやすい

models.pyの一部

from .database import Base

class User(Base):
  __tablename__ = "users"
  id = Column(Integer, primary_key=True, index=True)
  email = Column(String, unique=True, index=True)

database.pyの一部

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

なるほど、models.pyのクラスはSQLAlchemyパッケージの declarative_base() で生成したクラスを継承して生成されている

一方 schema.pyは

from pydantic import BaseModel

class User(BaseModel):
  email: str
  password: str

こっちはシンプルで pydanticクラスを継承して生成されている。

pydanticはデータベースとは直接の関係は一切ない

fastapiの公式ドキュメントには

  • SQLAlchemyは「モデル」という用語を、データベースと相互作用するこれらのクラスやインスタンスを指すのに使用しています。
  • しかしPydanticは「モデル」という用語を、データの検証、変換、ドキュメンタリーのクラスやインスタンスという、別のものを指すのにも使っています。

と書かれている。

原文は以下

SQLAlchemy uses the term "model" to refer to these classes and instances that interact with the database. But Pydantic also uses the term "model" to refer to something different, the data validation, conversion, and documentation classes and instances.

https://fastapi.tiangolo.com/tutorial/sql-databases/