所以我一直在遵循 Django 1.1 中的本指南,但我实际上是在使用 Django 2 来预填充 Django 数据库我使用的是 SQLite 数据库,这是我使用 Faker 库的代码,但它不会在我运行时运行想在 CMD 中运行它。如果可以,请你帮助我:
这是我的第一个文件,它是用于填充数据库的脚本:(populate_first_app.py)
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings')
import django
django.setup()
## FAKE POPULATION SCRIPT:
import random
from first_app.models import AccessRecord,Webpage,Topic
from faker import Faker
# Creating a fake generator:
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):
# 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.get_or_create(name = webpg, date = fake_date)[0]
if __name__ == '__main__':
print("Populating Script!")
populate(20)
print("Populating Complete!")
最后,这是我在这个项目中唯一的应用程序的 models.py 文件:
from django.db import models
class Topic(models.Model):
top_name = models.CharField(max_length = 255, unique = True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
# A Foreign key is grabbed from another table
topic = models.ForeignKey(Topic, on_delete=None)
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=None)
date = models.DateField()
def __str__(self):
# we cast it into string because self.date is a date object
return str(self.date)
智慧大石
相关分类