无法预先填充Django数据库

时间:2018-11-30 19:43:46

标签: python django python-3.x django-models faker

所以我一直在遵循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)

4 个答案:

答案 0 :(得分:1)

如果语句缩进错误,没有别的

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!")

答案 1 :(得分:0)

并不确定是否没有错误消息是什么问题,但是我的直觉是您无法在独立脚本中引导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帮助

答案 2 :(得分:0)

首先,您需要做python manage.py migrate

,然后分别为python manage.py makemigrations

然后给出类似的建议... AccessRecort更改为AccessRecord [y / N]? 按y

然后python mange.py migrate

  

要执行的操作:应用所有迁移:admin,auth,   contenttypes,first_app,会话正在运行迁移:正在应用   first_app.0002_auto_20190731_1445 ...确定

(MyDjangoEnv) C:\your\file\path\first_project>python populate_first_app.py

填充脚本!

填充完成!

答案 3 :(得分:0)

我确实检查了您的代码,但发现了为什么Django不创建伪数据的问题。 您已在“ populate_first_app.py”中缩进了 main 函数。删除缩进,您的代码应该可以正常工作。