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.
 
 
 
 

43 lines
1.8 KiB

from django.core.management.base import BaseCommand
from django.db import transaction
from apps.course.models import Course, CourseChapter
class Command(BaseCommand):
help = 'Migrates existing CourseLessons to be nested inside default CourseChapters (V2 Architecture).'
def handle(self, *args, **options):
self.stdout.write(self.style.WARNING("Starting data migration for Course Chapters..."))
courses = Course.objects.all()
courses_updated = 0
lessons_migrated = 0
# We wrap the whole loop in an atomic transaction.
# If anything crashes halfway through, the database rolls back to its original state!
with transaction.atomic():
for course in courses:
# Check if course has lessons but no chapters yet
if course.lessons.exists() and not course.chapters.exists():
self.stdout.write(f"Migrating course: {course.title}")
# Create a default 'General' chapter
default_chapter = CourseChapter.objects.create(
course=course,
title="General",
priority=1
)
# Attach all existing lessons to this new chapter
for index, course_lesson in enumerate(course.lessons.all().order_by('priority')):
course_lesson.chapter = default_chapter
course_lesson.priority = index + 1
course_lesson.save()
lessons_migrated += 1
courses_updated += 1
self.stdout.write(
self.style.SUCCESS(
f"🎉 Successfully migrated {lessons_migrated} lessons across {courses_updated} courses!"
)
)