完成了添加学生接口的自动生成studentno功能
This commit is contained in:
+26
-11
@@ -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
|
||||
Reference in New Issue
Block a user