Files
openclaw-monitor/code/backend/lobsters/management/commands/import_diaries.py
flying-hero 24e4ca2c82 feat: 创建 LobsterDiary 模型,支持数据库存储日记
- 创建 LobsterDiary 模型
  * 关联龙虾(ForeignKey)
  * 日期、标题、内容
  * 分类(成才之路/工作记忆/技术笔记)
  * 标签(JSONField)
  * Embedding 字段(预留 RAG 支持)
  * 数据库索引优化

- 数据库迁移
  * 添加 LobsterDiary 表
  * 添加索引:lobster+date, category+date, date

- 导入脚本
  * 创建 import_diaries 管理命令
  * 导入飞行侠的成才之路日记(3 篇)

- 更新 API
  * /api/lobsters/<id>/diary/dates/ - 从数据库查询
  * /api/lobsters/<id>/diary/<date>/ - 从数据库读取

- PostgreSQL 配置模板
  * settings_postgresql.py
  * 准备好 PostgreSQL 迁移

技术栈:SQLite(当前) → PostgreSQL(未来)
RAG 支持:预留 embedding 字段,未来可扩展

🗄️ 日记正式进入数据库时代!
2026-04-03 17:38:18 +08:00

85 lines
3.0 KiB
Python

#!/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} 篇日记'))