777ca50328
update. 调整融合主菜单与板块 update. 分离新闻模块
68 lines
2.1 KiB
Python
68 lines
2.1 KiB
Python
import os
|
|
import random
|
|
import sys
|
|
|
|
import django
|
|
|
|
# 配置 Django 环境
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") # 修改为你的 settings 路径
|
|
django.setup()
|
|
|
|
# 2. 导入 Faker 和 模型
|
|
from faker import Faker
|
|
from news.models import News, NewsSection
|
|
from users.models import User
|
|
|
|
# 初始化 Faker (zh_CN 表示生成中文数据)
|
|
fake = Faker('zh_CN')
|
|
|
|
|
|
def seed_news(count=20):
|
|
print(f"🚀 开始生成 {count} 条新闻数据...")
|
|
|
|
# --- 1. 获取关联数据 ---
|
|
# 获取所有板块
|
|
sections = list(NewsSection.objects.all())
|
|
# 获取所有用户
|
|
users = list(User.objects.all())
|
|
|
|
# 检查基础数据是否存在
|
|
if not sections:
|
|
print("❌ 错误:数据库中没有找到任何板块 (NewsSection)!请先添加板块。")
|
|
return
|
|
if not users:
|
|
print("⚠️ 警告:数据库中没有用户 (User),作者字段将设为空。")
|
|
|
|
# --- 2. 生成数据 ---
|
|
created_count = 0
|
|
for i in range(count):
|
|
# 随机选择一个板块
|
|
section = random.choice(sections)
|
|
# 随机选择一个作者 (如果有用户)
|
|
author = random.choice(users) if users else None
|
|
|
|
# 生成富文本内容 (模拟 CKEditor 输出的 HTML)
|
|
# paragrahs 生成多段文本,join 拼接
|
|
paragraphs = fake.paragraphs(nb=random.randint(3, 6))
|
|
content_html = "\n".join([f"<p>{p}</p>" for p in paragraphs])
|
|
|
|
# 创建新闻对象
|
|
news = News.objects.create(
|
|
title=fake.sentence(nb_words=random.randint(4, 8))[:-1], # 生成标题并去掉末尾句号
|
|
section=section,
|
|
author=author,
|
|
content=content_html,
|
|
is_published=True, # 默认已发布
|
|
# 封面图留空,因为自动生成图片文件比较复杂,建议手动上传测试图
|
|
)
|
|
|
|
created_count += 1
|
|
print(f" - [{section.name}] {news.title}")
|
|
|
|
print(f"✅ 成功生成 {created_count} 条新闻数据!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
seed_news(30)
|