在学习Django的情况下,我需要使用Faker模块用随机数据填充Sqlite。
在models.py下创建了几个模型:
from django.db import models
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic,on_delete=models.DO_NOTHING)
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):
return self.name
class AccessRecord(models.Model):
name = models.ForeignKey(Webpage,on_delete=models.DO_NOTHING)
date = models.DateField()
def __str__(self):
return str(self.date)
要随机填充这些模型,我使用以下脚本(populate_first_app.py):
import os
os.environment.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')
import django
django.setup()
##FAKE POP SCRIPT
import random
from first_app.models import AccessRecord,Webpage,Topic
from faker import Faker
fakegen = Faker()
topics = ['Search','Social','Marketplace','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):
top = add_topic()
fake_url = fakegen.url()
fake_date = fakegen.date()
fake_name = fakegen.company()
webpg = Webpage.objects.get_or_create(topic=top,url=fake_url,name=fake_name)[0]
acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0]
if __name__ == '__main__':
print('populating script!')
populate(20)
print('populating complete')
当我运行populate_first_app.py时,出现以下错误:
AttributeError:模块'os'没有属性'environment'
使用Visual Studio代码(v1.39.2),我陷入了困境。
视觉代码在以下几行上突出显示错误:
t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
“主题”类没有“对象” memberpylint(无成员)
我使用以下命令安装了pylint:
pip3 install pylint-django
但仍然卡住了。
答案 0 :(得分:3)
呼叫应为
os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')
有关更多详细信息,您可以查看以前的问题,例如: Is it safe to use os.environ.setdefault?