You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
3.0 KiB
78 lines
3.0 KiB
from django.core.management.base import BaseCommand
|
|
from django.db import transaction
|
|
|
|
from apps.quiz.models import Quiz, Question, QuizParticipant, ParticipantAnswer
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Clear all quiz-related data from the database'
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
'--confirm',
|
|
action='store_true',
|
|
help='Confirm that you want to delete all quiz data',
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
if not options['confirm']:
|
|
self.stdout.write(
|
|
self.style.WARNING(
|
|
'This command will delete ALL quiz-related data from the database!\n'
|
|
'This includes:\n'
|
|
'- All Quizzes\n'
|
|
'- All Questions\n'
|
|
'- All Quiz Participants\n'
|
|
'- All Participant Answers\n\n'
|
|
'Use --confirm flag to proceed with deletion.\n'
|
|
'Example: python manage.py clear_quiz_data --confirm'
|
|
)
|
|
)
|
|
return
|
|
|
|
try:
|
|
with transaction.atomic():
|
|
# Count records before deletion
|
|
participant_answers_count = ParticipantAnswer.objects.count()
|
|
quiz_participants_count = QuizParticipant.objects.count()
|
|
questions_count = Question.objects.count()
|
|
quizzes_count = Quiz.objects.count()
|
|
|
|
self.stdout.write(
|
|
f'Found {participant_answers_count} participant answers, '
|
|
f'{quiz_participants_count} quiz participants, '
|
|
f'{questions_count} questions, and '
|
|
f'{quizzes_count} quizzes.'
|
|
)
|
|
|
|
# Delete in order to respect foreign key constraints
|
|
# ParticipantAnswer -> QuizParticipant -> Quiz
|
|
# Question -> Quiz
|
|
|
|
self.stdout.write('Deleting participant answers...')
|
|
ParticipantAnswer.objects.all().delete()
|
|
|
|
self.stdout.write('Deleting quiz participants...')
|
|
QuizParticipant.objects.all().delete()
|
|
|
|
self.stdout.write('Deleting questions...')
|
|
Question.objects.all().delete()
|
|
|
|
self.stdout.write('Deleting quizzes...')
|
|
Quiz.objects.all().delete()
|
|
|
|
self.stdout.write(
|
|
self.style.SUCCESS(
|
|
f'Successfully deleted all quiz data:\n'
|
|
f'- {participant_answers_count} participant answers\n'
|
|
f'- {quiz_participants_count} quiz participants\n'
|
|
f'- {questions_count} questions\n'
|
|
f'- {quizzes_count} quizzes'
|
|
)
|
|
)
|
|
|
|
except Exception as e:
|
|
self.stdout.write(
|
|
self.style.ERROR(f'Error occurred while clearing quiz data: {str(e)}')
|
|
)
|
|
raise
|