Files
sqlalchemy_fastapi_demo_1/scheme/students.py
T

68 lines
2.8 KiB
Python
Raw Normal View History

2026-09-21 19:15:28 +08:00
# scheme/student.py
from pydantic import BaseModel, Field,model_validator
from datetime import datetime, date
from typing import Optional
# ---------- 请求体模型 ----------
class StudentCreate(BaseModel):
stu_id: int = Field(..., ge = 1)
class_id: int = Field(..., ge = 1)
advisor_id: int = Field(..., ge=1, description="顾问老师id,对应 advisors.advisor_id")
stu_name: str = Field(..., min_length=1, max_length=10)
native_place: str = Field(..., min_length=1, max_length=30)
graduate_school: str = Field(..., min_length=1, max_length=50)
education: str = Field(..., min_length=1, max_length=10)
major: str = Field(..., min_length=1, max_length=20)
age: int = Field(..., ge = 18, le =40)
gender: str = Field(..., min_length=1, max_length=20)
graduate_time:date= Field(...)
enroll_time:date= Field(...)
# 模型校验,时间判断
# @model_validator (mode = "after")
# def check_time(self):
# # 入学时间不能晚于就业时间
# if self.graduate_time is not None:
# if self.graduate_time < self.enroll_time:
# raise ValueError ("毕业时间不能早于入学时间!!!")
# # 简历开放时间不能早于入学时间
# # if self.employment_open_time < self.enroll_time:
# # raise ValueError("简历开放时间不能早于入学时间")
# # 简历开放时间不能晚于毕业时间
# if self.graduate_time is not None:
# if self.graduate_time < self.employment_open_time:
# raise ValueError("简历开放时间不能晚于毕业时间!!!")
# # mode="after" 的校验器必须返回 self,否则 Pydantic v2 会把整个模型变成 None
# return self
class StudentUpdate(BaseModel):
class_id: Optional[int] = Field(None)
advisor_id: Optional[int] = Field(None, ge=1)
stu_name: Optional[str] = Field(None, min_length=1, max_length=10)
native_place: Optional[str] = Field(None, min_length=1, max_length=30)
graduate_school: Optional[str] = Field(None, min_length=1, max_length=50)
education: Optional[str] = Field(None, min_length=1, max_length=10)
major: Optional[str] = Field(None, min_length=1, max_length=20)
age: Optional[int] = Field(None, ge = 18, le =40)
gender: Optional[str] = Field(None, min_length=1, max_length=20)
# ----------响应体模型-------------
class StudentResponse(BaseModel):
stu_id: int
class_id: int # 数据库非空,这里必须是 int
stu_name: str
native_place: str
graduate_school: Optional[str]
education: str
major: Optional[str]
# 敏感字段已在此模型中脱敏
class Config:
from_attributes = True #支持orm对象转换,让pydantic可以读取ORM数据库对象(SQLAlchemy模型)