From 0bc336a7d05bbb2d46b5ba12315050708cedaf01 Mon Sep 17 00:00:00 2001 From: Daniel Date: Wed, 1 Apr 2026 02:36:25 +0200 Subject: [PATCH] Quiz delete: detach questions to bank instead of deleting them When deleting a quiz: - Questions shared with other quizzes stay linked to those quizzes - Questions exclusive to this quiz are detached (source_quiz_id cleared) and remain in the Question Bank as orphaned questions, not deleted - This preserves the question bank integrity Also improves manage.py CLI with extract, list-sections, and jobs commands Co-Authored-By: Claude Sonnet 4.6 (1M context) --- backend/app/routers/quizzes.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/backend/app/routers/quizzes.py b/backend/app/routers/quizzes.py index 20f4ef4..2025288 100644 --- a/backend/app/routers/quizzes.py +++ b/backend/app/routers/quizzes.py @@ -441,8 +441,28 @@ def delete_quiz( db: Session = Depends(get_db), current_user: User = Depends(require_moderator), ): + """Delete quiz. Questions shared with other quizzes stay in the bank. + Questions only in this quiz are detached (source_quiz_id cleared) so they + remain in the bank instead of being deleted.""" + from app.models.quiz_question_link import QuizQuestionLink + quiz = db.query(Quiz).filter(Quiz.id == quiz_id).first() if not quiz: raise HTTPException(status_code=404, detail="Quiz not found") - db.delete(quiz) + + # For each question linked to this quiz: if no other quiz uses it, + # detach it (clear source_quiz_id) so it stays as a bank-only question + links = db.query(QuizQuestionLink).filter(QuizQuestionLink.quiz_id == quiz_id).all() + for link in links: + other = db.query(QuizQuestionLink).filter( + QuizQuestionLink.question_id == link.question_id, + QuizQuestionLink.quiz_id != quiz_id, + ).count() + if other == 0: + # Detach from this quiz but keep in bank + db.query(QuestionModel).filter(QuestionModel.id == link.question_id).update( + {"quiz_id": None} # source_quiz_id → null + ) + + db.delete(quiz) # cascades quiz_question_links db.commit()