In the context of learning Django, I need to populate Sqlite with random data using Faker module.
Several models have been created under 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)
To randomly populate these models, I'm using the following script (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')
When I'm running populate_first_app.py, I got the following error:
AttributeError: module 'os' has no attribute 'environment'
Using Visual Studio Code (v1.39.2), I'm stuck.
Visual code is highlighting error on following lines:
t = Topic.objects.get_or_create(top_name=random.choice(topics))[0]
Class 'Topic' has no 'objects' memberpylint(no-member)
I installed pylint using the following command:
pip3 install pylint-django
But still stuck.
The call should be
os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')
For more details you can see previous questions, like this one: Is it safe to use os.environ.setdefault?