Files
server/news/seeder.py
T

100 lines
3.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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"<p><strong>【摘要】</strong> {fake.sentence(nb_words=10)}</p>")
# B. 正文第一段
html_parts.append(f"<p>{fake.paragraph(nb_sentences=4)}</p>")
# 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'<div style="text-align: center; margin: 20px 0;"><img src="https://placehold.co/{img_width}x{img_height}/23418A/FFF?text={"+".join(img_text)}" style="max-width: 100%; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"></div>')
# D. 正文中间段落
html_parts.append(f"<p>{fake.paragraph(nb_sentences=5)}</p>")
# E. 随机插入引用块 (增加排版层次感)
if random.random() > 0.6:
quote = fake.sentence(nb_words=8)
html_parts.append(
f'<blockquote style="border-left: 5px solid #23418A; padding: 10px 20px; margin: 20px 0; background: #f8f9fa; color: #555;"><i>"{quote}"</i></blockquote>')
# F. 随机插入无序列表 (模拟要点陈述)
if random.random() > 0.7:
list_items = "".join([f"<li>{fake.sentence()}</li>" for _ in range(3)])
html_parts.append(f"<ul style='margin: 20px 0; padding-left: 20px;'>{list_items}</ul>")
# G. 加粗和斜体混合段落
p1 = fake.paragraph(nb_sentences=2)
p2 = fake.paragraph(nb_sentences=2)
html_parts.append(f"<p>{p1} <strong style='color: #23418A;'>{fake.words(nb=4, unique=True)}</strong> {p2}</p>")
# H. 结尾
html_parts.append(f"<p>{fake.paragraph(nb_sentences=3)}</p>")
# 拼接最终 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)