fix: ExamService.start_exam返回ID避免懒加载
All checks were successful
continuous-integration/drone/push Build is passing

修改start_exam返回exam.id而不是整个Exam对象,
彻底避免SQLAlchemy异步会话的懒加载问题
This commit is contained in:
yuliang_guo
2026-01-31 11:21:39 +08:00
parent 50c511d825
commit e1d10605c9
2 changed files with 8 additions and 6 deletions

View File

@@ -66,7 +66,7 @@ async def start_exam(
user_id = current_user.id user_id = current_user.id
username = current_user.username username = current_user.username
exam = await ExamService.start_exam( exam_id = await ExamService.start_exam(
db=db, db=db,
user_id=user_id, user_id=user_id,
course_id=request.course_id, course_id=request.course_id,
@@ -96,7 +96,7 @@ async def start_exam(
) )
) )
return ResponseModel(code=200, data=StartExamResponse(exam_id=exam.id), message="考试开始") return ResponseModel(code=200, data=StartExamResponse(exam_id=exam_id), message="考试开始")
@router.post("/submit", response_model=ResponseModel[SubmitExamResponse]) @router.post("/submit", response_model=ResponseModel[SubmitExamResponse])

View File

@@ -20,7 +20,7 @@ class ExamService:
@staticmethod @staticmethod
async def start_exam( async def start_exam(
db: AsyncSession, user_id: int, course_id: int, question_count: int = 10 db: AsyncSession, user_id: int, course_id: int, question_count: int = 10
) -> Exam: ) -> int:
""" """
开始考试 开始考试
@@ -31,7 +31,7 @@ class ExamService:
question_count: 题目数量 question_count: 题目数量
Returns: Returns:
Exam: 考试实例 int: 考试ID
""" """
# 检查课程是否存在 # 检查课程是否存在
course = await db.get(Course, course_id) course = await db.get(Course, course_id)
@@ -94,7 +94,9 @@ class ExamService:
await db.commit() await db.commit()
await db.refresh(exam) await db.refresh(exam)
return exam # 返回exam.id而不是整个对象避免懒加载问题
exam_id = exam.id
return exam_id
@staticmethod @staticmethod
async def submit_exam( async def submit_exam(