用django写博客的时候,批量生成用户和文章是个体力活,在狗书中提到了使用forgerypy如何批量创建用户和文章。这里依据
flask
的版本,照猫画虎实现一个django
版的。
准备工作
首先forgerpy的安装,forgerpy不知道是版本有问题,有些代码是依据py2生成的,运行中会出错,这里使用forgerpy3,详细语法参考网站。
安装
pip install forerypy3
模型说明
这里假定你扩展了一下用户模型作为作者(Author
),并且有一个记录博客文章的模型为Artical
,为了方便,一切从简。
from django.db import models
from django.contrib.auth.models import User
class Author(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
nickname = models.CharField(max_length=30)
class Artical(models.Model):
title = models.CharField(max_length =250)
body = models.TextField()
create_time = models.DateField()
modified_time = models.DateField()
author = models.ForeignKey(Author,on_delete=models.CASCADE)
静态方法
下面开始在模型中添加静态方法用于创建用户和文章,为了看起来简单,这里把原来的模型和静态方法都贴出来。
from django.db import models
from django.contrib.auth.models import User
class Author(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
nickname = models.CharField(max_length=30)
@staticmethod
def fake_user(count=20):
import forgery_py as fg
from random import seed
seed()
for i in range(count):
#首先创建用户并保存
user =User(username=fg.internet.user_name(),
password = fg.lorem_ipsum.word(),
)
try:
user.save()
except Exception as e:
continue
#然后将取得的用户关联到扩展的用户模型
author = Author(user=user,nickname = fg.name.last_name())
author.save()
def __repr__(self):
return self.nickname
class Artical(models.Model):
title = models.CharField(max_length =250)
body= models.TextField()
create_time = models.DateField()
modified_time = models.DateField()
author = models.ForeignKey(Author,on_delete=models.CASCADE)
def __repr__(self):
return self.title
@staticmethod
def fake_post(count=100):
from random import seed,randint
import forgery_py as fg
seed()
user_count = Author.objects.all().count()
for i in range(count):
#这里需要注意的是:django的id是从1开始的,而不是0
u = Author.objects.get(pk = randint(1,user_count))
p = Artical(
title = fg.lorem_ipsum.title(),
body = fg.lorem_ipsum.paragraphs(5),
create_time = fg.date.date(),
modified_time = fg.date.date(),
author = u,
)
p.save()
创建用户和文章
这里就不多说了,这是我创建的时候的效果
python3 manage.py shell
In [1]: from blog.models import Author
In [2]: Author.fake_user(20)
In [3]: from blog.models import Artical
In [4]: Artical.fake_post(100)