diff --git a/api/student.py b/api/student.py index 444dea2..50311ab 100644 --- a/api/student.py +++ b/api/student.py @@ -4,7 +4,7 @@ from schemas.student import StudentCreate from sqlalchemy.orm import Session student_router = APIRouter() -@student_router.post("") +@student_router.post("",summary='添加学生') def create_student(request:StudentCreate,db:Session = Depends(get_db)): d = request.model_dump() r = create_students(d,db) @@ -12,3 +12,5 @@ def create_student(request:StudentCreate,db:Session = Depends(get_db)): raise HTTPException(status_code=500,detail='服务器繁忙,请稍后添加!') return {'code':200,'detail':"添加学生成功"} + + diff --git a/dao/student.py b/dao/student.py index 49991d7..9fc678b 100644 --- a/dao/student.py +++ b/dao/student.py @@ -1,17 +1,32 @@ from schemas.student import * -from fastapi import Depends from core.database import get_db from models.student import * -from utils.code_generator import generate_no from sqlalchemy.orm import Session -def create_students(d,db:Session = Depends(get_db)): - stu = Student(**d) - try: - db.add(stu) - db.commit() - except: - return False - else: - return True +def create_students(d: dict, db: Session): + stu = Student(**d) + + try: + # 1. 添加到 Session + db.add(stu) + + # 2. flush,让 MySQL 先生成自增 id + db.flush() + + # 3. 根据 id 生成学生编号 + if not stu.student_no: + stu.student_no = f"STU{stu.id:04d}" + + # 4. 提交事务 + db.commit() + + # 5. 刷新对象,拿到数据库最终数据 + db.refresh(stu) + + return stu + + except Exception as e: + db.rollback() + print(f"插入学生失败: {e}") + return None \ No newline at end of file diff --git a/models/student.py b/models/student.py index ab805e4..881c9b8 100644 --- a/models/student.py +++ b/models/student.py @@ -10,7 +10,7 @@ class Student(Base): , comment = '学生编号,自增主键' ) student_no = Column(VARCHAR(50) - , unique = True) + ,nullable = True) student_name = Column(VARCHAR(50)) class_id = Column(Integer ,ForeignKey('class_info_detail.id') diff --git a/schemas/student.py b/schemas/student.py index 64c42bb..6265446 100644 --- a/schemas/student.py +++ b/schemas/student.py @@ -2,7 +2,7 @@ from pydantic import BaseModel from datetime import date class StudentCreate(BaseModel): - student_no: str|None = None + student_no:str|None = None student_name: str class_id: int consultant_id: int | None = None