的缩进
if __name__ == '__main__':
是错误的。正确的方法是在
populate
功能如下:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
import django
django.setup()
#FAKE POP SCRIPT
import random
from first_app.models import Topic, AccessRecord, Webpage
from faker import Faker
fakegen = Faker()
topics = ['Search', 'Social', 'Market', 'News', 'Games']
def add_topic():
t = Topic.objects.get_or_create(top_name = random.choice(topics))[0]
t.save()
return t
def populate(N=5):
for entry in range(N):
#Get the topic for the entry
top = add_topic()
#Create the fake data for that entry
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
#Create the new webpage entry
webpg = Webpage.objects.get_or_create(topic = top,url = fake_url, name = fake_name)[0]
#Create a fake access record for that webpage
acc_rec = AccessRecord.objects.get_or_create(name = webpg, date = fake_date)[0]
if __name__ == '__main__':
print("populating script!")
populate(20)
print("populating complete!")
使用进行测试
minimal-reproducible-example
它的工作原理是:
from faker import Faker
fakegen = Faker()
def populate(N=5):
for _ in range(N):
#Create the fake data for that entry
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
print(fake_url, fake_date, fake_name)
if __name__ == '__main__':
print("populating script!")
populate(20)
print("populating complete!")
输出
populating script!
https://www.jackson-allen.com/ 1987-05-26 Rogers, Adams and Keith
https://jefferson-smith.com/ 1976-01-05 Murphy-Smith
https://swanson-evans.info/ 1986-02-10 Martin-Fields
http://www.fleming-miller.com/ 2010-06-18 Tanner-Frost
https://higgins.net/ 2008-11-20 Mccoy-Jones
http://www.cunningham.net/ 2017-02-10 Kramer-Mccall
http://wright-mills.com/ 1973-08-14 Moran, Humphrey and Spears
https://diaz.com/ 2017-05-16 Thomas Ltd
http://klein-flores.com/ 1988-12-18 Gentry Group
http://www.potts.com/ 1986-01-29 King-Moore
https://perez.biz/ 1998-09-09 Robinson, Fowler and Callahan
https://khan.com/ 2016-06-17 Wells-Mcdonald
https://manning-garcia.com/ 2011-04-28 Jenkins, Crawford and Garcia
https://foster.com/ 2004-09-26 Rodriguez Ltd
https://www.wright.com/ 1987-10-06 Velasquez Group
http://www.davis.net/ 1985-07-28 Armstrong, Wood and Grant
http://www.blevins.biz/ 1984-03-10 Ross LLC
http://www.mcintyre.biz/ 1971-11-23 Daugherty-Jackson
http://thompson.com/ 1980-07-15 Payne, Powers and Wilson
https://www.thomas-mason.com/ 2002-08-09 Pacheco, Palmer and Hernandez
populating complete!