这是我的模特。py
from django.db import models
# Create your models here.
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.PROTECT)
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.PROTECT)
date = models.DateField()
def __str__(self):
return self.date
这是我的populate.py
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE','first_project.settings')
import django
django.setup()
##fake pop script
import random
from first_app import Topic,Webpage,AccessRecord
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):
#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.name()
#create a fake 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.objects.get_or_create(name=webpg,date=fake_date)[0]
if __name__ == '__main__':
print("population script")
populate(20)
print("populate complete")
我正在尝试运行populate.py,但出现错误
Traceback (most recent call last):
File "populate_first_app.py", line 9, in <module>
from first_app import Topic,Webpage,AccessRecord
ImportError: cannot import name 'Topic' from 'first_app' (/home/hamid/Desktop/my_django_stuff/first
_project/first_app/__init__.py)
答案 0 :(得分:3)
欢迎使用StackOverflow,哈米德:)
如果models.py
在first_app
目录中,则需要从以下位置更改导入行:
from first_app import Topic,Webpage,AccessRecord
收件人
from first_app.models import Topic,Webpage,AccessRecord
否则,导入将在first_class/__init__.py
中查找类,这就是为什么会出现该错误的原因。有关更多详细信息,您可以阅读Python's import system