把 JSON 转换成可直接运行的 SQLAlchemy 2.0 声明式模型:包含 Base(DeclarativeBase) 类、配合 mapped_column() 的 Mapped[...] 类型提示、nullable 标志、__tablename__ 以及 Integer 主键。
当 FastAPI 或 Flask 后端需要把请求 JSON 或从其他系统下载的数据,存进一张还没有模型的表时,这是个不错的起点。
nullable=True。模型名 中输入类名(默认 MyModel);__tablename__ 是该名称的大写 snake case 形式。models.py。如果项目里已经有 Base,请删掉生成的那个并导入你自己的,让所有模型共用同一个 metadata。{
"isbn": "978-0-13-468599-1",
"title": "The Pragmatic Programmer",
"pages": 352,
"rating": 4.7,
"available": true,
"published_at": "2019-09-13"
}from datetime import date
from sqlalchemy import Boolean, Date, Float, Integer, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = "BOOK"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
isbn: Mapped[str] = mapped_column(String(255), nullable=False)
title: Mapped[str] = mapped_column(String(255), nullable=False)
pages: Mapped[int] = mapped_column(Integer, nullable=False)
rating: Mapped[float] = mapped_column(Float, nullable=False)
available: Mapped[bool] = mapped_column(Boolean, nullable=False)
published_at: Mapped[date] = mapped_column(Date, nullable=False)带连字符的 isbn 仍是 String(255),pages 变成 Integer,rating 变成 Float,只有日期没有时间的 published_at 变成带 date 提示的 Date。每个值都存在,所以所有列都是 nullable=False。
class Base(DeclarativeBase): pass,并且只导入实际用到的 SQLAlchemy 类型和 datetime 名称。Integer/int(大数值用 BigInteger),小数 → Float,布尔值 → Boolean,YYYY-MM-DD → Date/date,日期时间 → DateTime/datetime,对象和数组 → 配合 dict/list 的 JSON。String(255);示例值超过 255 个字符时为 Text,这样在 MySQL 上也能建表。publishedAt、home-url),原始 key 会作为列名传入:mapped_column("publishedAt", ...)。Python 关键字和 metadata 会加上后缀 _。nullable=True 之外,类型提示也写成 Mapped[str | None]。Integer,在 SQLite 上同样会自增;JSON 中的字符串 id 会变成 String(255) 主键,很大的整数 id 则使用 BigInteger().with_variant(Integer, "sqlite")。如果已经有为 Pydantic schema 准备的示例请求 JSON,就用同一份 JSON 生成 SQLAlchemy 模型,马上写出 session.add(Book(**payload)) 的流程。
模型注册到 Base.metadata 之后,alembic revision --autogenerate 会根据这个类生成 create_table 迁移。
str | None 提示需要 Python 3.10 及以上。旧版本请配合 from typing import Optional 写成 Optional[str]。__tablename__ 是大写的(BOOK)。这样在 PostgreSQL 的原生 SQL 中需要加引号,所以很多项目会改成 books。db.Model 而不是生成的 Base。Float 是二进制浮点数;价格请使用配合 Decimal 的 Numeric(10, 2)。id 用 Integer 而不是 BigInteger?SQLite 只会让声明为 INTEGER PRIMARY KEY 的列自增,所以 Integer 能让本地测试和生产环境表现一致。只有当数据中已有超过 32 位的 id 时,主键才会改用带 SQLite 变体的 BigInteger。
__table_args__)设置吗?没有。表会建在连接的默认 schema 中。要指定 PostgreSQL 的其他 schema,请自行添加 __table_args__ = {"schema": "billing"}。
Column() 语法吗?输出只有 2.0 风格(Mapped、mapped_column、DeclarativeBase)。要用 1.4,请使用 declarative_base(),并把每一行改写成 title = Column(String(255), nullable=False)。