#!/usr/bin/env python """ 导入现有日记文件到数据库 使用方法: python manage.py import_diaries """ from django.core.management.base import BaseCommand from pathlib import Path from datetime import datetime from lobsters.models import Lobster, LobsterDiary class Command(BaseCommand): help = '导入现有日记文件到数据库' def handle(self, *args, **kwargs): self.stdout.write('🚀 开始导入日记...') # 获取飞行侠 try: feixingxia = Lobster.objects.get(name='飞行侠') self.stdout.write(f'✅ 找到龙虾:{feixingxia}') except Lobster.DoesNotExist: self.stdout.write(self.style.ERROR('❌ 未找到飞行侠')) return # 日记目录 diary_dir = Path('/home/node/.openclaw/workspace/flying-hero/memory/成才之路') if not diary_dir.exists(): self.stdout.write(self.style.ERROR(f'❌ 日记目录不存在:{diary_dir}')) return self.stdout.write(f'📂 扫描目录:{diary_dir}') # 导入日记 imported_count = 0 for file in diary_dir.glob('*.md'): # 提取日期 filename = file.name if filename.endswith('-故事版.md'): date_str = filename.replace('-故事版.md', '') category = 'chengcai' title = f'成才之路 · 故事版 · {date_str}' elif filename.endswith('-技术版.md'): date_str = filename.replace('-技术版.md', '') category = 'chengcai' title = f'成才之路 · 技术版 · {date_str}' else: date_str = filename.replace('.md', '') category = 'chengcai' title = f'成才之路 · {date_str}' try: date = datetime.strptime(date_str, '%Y-%m-%d').date() except ValueError: self.stdout.write(self.style.WARNING(f'⚠️ 跳过无效日期文件:{filename}')) continue # 读取内容 content = file.read_text(encoding='utf-8') # 创建或更新日记 diary, created = LobsterDiary.objects.update_or_create( lobster=feixingxia, date=date, category=category, defaults={ 'title': title, 'content': content, 'tags': ['成才之路', '成长日记'], } ) if created: self.stdout.write(self.style.SUCCESS(f'✅ 导入:{title}')) else: self.stdout.write(self.style.WARNING(f'🔄 更新:{title}')) imported_count += 1 self.stdout.write(self.style.SUCCESS(f'\n🎉 导入完成!共导入 {imported_count} 篇日记'))