| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- """
- 数据初始化脚本
- 从模型列表.json文件导入数据到数据库
- 需求: 5.1, 5.2, 5.3, 5.4, 5.5
- """
- import json
- import sys
- from pathlib import Path
- sys.path.insert(0, str(Path(__file__).parent.parent))
- from app.database import SessionLocal
- from app.models.model import ModelNew
- def init_data():
- """初始化模型数据"""
- json_path = Path(__file__).parent.parent.parent / "模型列表.json"
-
- with open(json_path, 'r', encoding='utf-8') as f:
- models_data = json.load(f)
-
- db = SessionLocal()
- inserted = 0
- updated = 0
-
- for item in models_data:
- existing = db.query(Model).filter(Model.title == item['title']).first()
-
- if existing:
- existing.img = item.get('img', '')
- existing.name = item.get('name', '')
- existing.tag1 = item.get('tag1', '')
- existing.description = item.get('description', '')
- existing.keyword = item.get('keyword', '')
- existing.time = item.get('time', '')
- existing.tag2 = item.get('tag2', '')
- updated += 1
- else:
- model = Model(
- title=item['title'],
- img=item.get('img', ''),
- name=item.get('name', ''),
- tag1=item.get('tag1', ''),
- description=item.get('description', ''),
- keyword=item.get('keyword', ''),
- time=item.get('time', ''),
- tag2=item.get('tag2', '')
- )
- db.add(model)
- inserted += 1
-
- db.commit()
- db.close()
-
- print(f"数据导入完成: 新增 {inserted} 条, 更新 {updated} 条, 共 {inserted + updated} 条")
- if __name__ == "__main__":
- init_data()
|