Files
sqlalchemy_fastapi_demo_1/scheme/c_lass.py
T

35 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pydantic import BaseModel, Field, ConfigDict # BaseModel=模型基类,Field=字段规则,ConfigDict=模型配置
from datetime import date # Python的日期类型(只有年月日)
from typing import Optional # Optional[X] 表示"可以是X,也可以是None"
# ---------------- 请求模型 ----------------
# 新增班级:class_id、start_time 必填
# 请求模型 = 前端传过来的数据长什么样,FastAPI自动帮你校验
class ClassCreate(BaseModel):# 新增班级的入参模型:POST新增时,请求体必须符合这个结构
class_id: int = Field(..., ge=1, description="班级编号,正整数,不能重复")
start_time: date = Field(..., description="开班日期,格式 yyyy-MM-dd")
# description:这行字会显示在Swagger文档里,方便前端看
# 修改班级:字段可选,前端传哪个改哪个(局部更新)
class ClassUpdate(BaseModel):
# class_id: int = Field( ge=1, description="班级编号,可选") 被注释掉 = 不允许修改班级编号
start_time: Optional[date] = Field(None, description="开班日期,格式 yyyy-MM-dd")
# Optional[date] = 可以传日期也可以不传;Field(None) = 不传时默认值是None
# ---------------- 响应模型 ----------------
# 响应模型:后端返回给前端的数据结构,from_attributes 允许直接从 ORM (Classinfo实例)的属性取值,不用手动一个个赋值
class ClassResponse(BaseModel):
model_config = ConfigDict(from_attributes=True)
class_id: int # 返回字段:班级编号
start_time: date# 返回字段:开班日期
#逻辑:**三个模型管三种场景**—— 新增(必填)、修改(可选)、响应(输出)。
# 前端传错类型 / 缺字段,FastAPI 直接返回 422,不会把脏数据送进数据库。