66 lines
2.5 KiB
Python
66 lines
2.5 KiB
Python
# dao/student_dao.py
|
|
# 本文件封装对学生表的所有数据库操作(增、删、改、查)
|
|
from fastapi import HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from model.student import Student
|
|
from scheme.students import StudentCreate, StudentUpdate
|
|
|
|
|
|
class StudentDAO:
|
|
# 多条件查询学生列表(编号、姓名、班级等,条件可以叠加)
|
|
@staticmethod
|
|
def get_list(db: Session, sid=None, name=None, cid=None,
|
|
gender=None, education=None, page=1, size=10):
|
|
query = db.query(Student).filter(Student.flag == 1) # flag=1 才是有效数据
|
|
# 传了哪个条件就追加哪个过滤条件
|
|
if sid :
|
|
query = query.filter(Student.sid == sid)
|
|
if name:
|
|
query = query.filter(Student.name.like(f"%{name}%")) # 姓名模糊查询
|
|
if cid :
|
|
query = query.filter(Student.cid == cid)
|
|
if gender:
|
|
query=query.filter(Student.gender == gender)
|
|
if education:
|
|
query=query.filter(Student.education == education)
|
|
total = query.count() # 先算总条数(分页要用)
|
|
items = query.order_by(Student.sid).offset((page - 1) * size).limit(size).all()
|
|
return total, items
|
|
|
|
# 按学生id查单个学生
|
|
@staticmethod
|
|
def get_by_id(db: Session, sid: int):
|
|
student = db.query(Student).filter(Student.sid == sid, Student.flag == 1).first()
|
|
if not student:
|
|
raise HTTPException(status_code=404, detail=f"学生 {sid} 不存在")
|
|
return student
|
|
|
|
# 新增学生
|
|
@staticmethod
|
|
def create(db: Session, data: StudentCreate):
|
|
student = Student(**data.model_dump())
|
|
student.flag = 1 # 新数据默认是正常状态
|
|
db.add(student)
|
|
db.commit()
|
|
db.refresh(student) # 刷新后能拿到数据库生成的自增学号
|
|
return student
|
|
|
|
# 更新学生信息
|
|
@staticmethod
|
|
def update(db: Session, sid: int, data: StudentUpdate):
|
|
update_data = data.model_dump(exclude_unset=True)
|
|
db.query(Student) \
|
|
.filter(Student.sid == sid) \
|
|
.update(update_data)
|
|
db.commit()
|
|
return StudentDAO.get_by_id(db, sid)
|
|
|
|
# 逻辑删除学生(flag 改为 0,不真删数据)
|
|
@staticmethod
|
|
def delete(db: Session, sid: int):
|
|
student = StudentDAO.get_by_id(db, sid)
|
|
student.flag = 0
|
|
db.commit()
|
|
db.refresh(student)
|
|
return student
|