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 created_count = 0 for i in range(count): section = random.choice(sections) author = random.choice(users) if users else None # --- 2. 构建丰富的 HTML 内容 --- html_parts = [] # A. 开头:一段引言或摘要 if random.random() > 0.5: html_parts.append(f"
【摘要】 {fake.sentence(nb_words=10)}
") # B. 正文第一段 html_parts.append(f"{fake.paragraph(nb_sentences=4)}
") # C. 随机插入图片占位符 (模拟上传的封面或插图) # 使用 placehold.co 生成带文字的灰色占位图 img_width = random.choice([600, 800]) img_height = random.choice([300, 400]) img_text = fake.words(nb=3, unique=True) html_parts.append( f'{fake.paragraph(nb_sentences=5)}
") # E. 随机插入引用块 (增加排版层次感) if random.random() > 0.6: quote = fake.sentence(nb_words=8) html_parts.append( f'"{quote}"') # F. 随机插入无序列表 (模拟要点陈述) if random.random() > 0.7: list_items = "".join([f"
{p1} {fake.words(nb=4, unique=True)} {p2}
") # H. 结尾 html_parts.append(f"{fake.paragraph(nb_sentences=3)}
") # 拼接最终 HTML content_html = "\n".join(html_parts) # --- 3. 创建对象 --- news = News.objects.create( title=fake.sentence(nb_words=random.randint(4, 8))[:-1], section=section, author=author, content=content_html, is_published=True, # 可以在这里加上摘要字段,如果有的话 # summary=fake.paragraph(nb_sentences=1) ) created_count += 1 print(f" - [{section.title}] {news.title}") print(f"✅ 成功生成 {created_count} 条富文本新闻数据!") if __name__ == "__main__": seed_news(120)