Files
chunyu_project/learn/management/commands/seed_python_content.py
T
2026-08-05 23:59:15 +08:00

51 lines
1.9 KiB
Python

import json
import os
from django.core.management.base import BaseCommand
from learn.models import Course, Chapter, ChapterContent
class Command(BaseCommand):
help = '为Python基础课程填充教学内容'
def handle(self, *args, **options):
python_course = Course.objects.filter(title__icontains='Python').first()
if not python_course:
self.stdout.write(self.style.ERROR('未找到Python课程,请先运行 seed_courses'))
return
# Load content from JSON file
json_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'python_content.json')
if not os.path.exists(json_path):
self.stdout.write(self.style.ERROR(f'内容文件不存在: {json_path}'))
return
with open(json_path, 'r', encoding='utf-8') as f:
chapters_data = json.load(f)
created_count = 0
for ch_data in chapters_data:
chapter, created = Chapter.objects.update_or_create(
course=python_course,
sort_order=ch_data['sort_order'],
defaults={
'title': ch_data['title'],
'duration': ch_data['duration'],
'is_free': ch_data['is_free'],
'video_url': ch_data['video_url'],
}
)
if created or not ChapterContent.objects.filter(chapter=chapter).exists():
ChapterContent.objects.update_or_create(
chapter=chapter,
defaults={
'content_md': ch_data['content_md'],
'content_html': ch_data['content_md'],
}
)
if created:
created_count += 1
self.stdout.write(self.style.SUCCESS(f'成功为Python课程填充 {len(chapters_data)} 章内容'))