所以我一直遵循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)
最佳答案
目前尚不清楚您的问题出在什么地方而没有错误消息,但是我的直觉是您无法在独立脚本中引导Django环境。
Django具有特殊的功能来构建“命令”,您可以在Django环境中运行它,而不必像在populate_first_app.py中那样进行“设置”。
Django Documentation for Custom Commands
在上面的示例中,您希望将“ populate_first_app.py”移动到“ first_app / management / commands / populate_first_app.py”处。然后,您需要将函数放置在BaseCommand中:
from django.core.management.base import BaseCommand, CommandError
from polls.models import Question as Poll
# .. other imports
class Command(BaseCommand):
help = 'Populates test data in first_app'
def add_arguments(self, parser):
parser.add_argument('n', type=int)
def handle(self, *args, **options):
fakegen = Faker()
for entry in range(args.n):
#.. generate each entry
获得此命令后,即可从manage.py运行它:
manage.py populate_first_app -n 20
好处是当其他人想要使用它时,他们可以在运行时看到它
manage.py帮助
关于python - 无法预先填充Django数据库,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53563913/