python - ImportError:无法从“first_app”导入名称“Topic”
问题描述
这是我的models.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)
解决方案
欢迎来到 StackOverflow,Hamid :)
如果models.py
在first_app
目录内,则需要将导入行更改为:
from first_app import Topic,Webpage,AccessRecord
至
from first_app.models import Topic,Webpage,AccessRecord
否则,导入将在 中查找类first_class/__init__.py
,这就是您收到该错误的原因。有关更多详细信息,您可以阅读Python 的导入系统
推荐阅读
- javascript - 如何获取对象数组中所有对象的列表?
- docker - 在 Raspberry Pi 4 上安装 Docker 时出错
- python - 如何使用 selenium python 访问单击事件后加载的元素
- elasticsearch - 如何找到与 Elastic 搜索别名关联的所有索引?
- blazor - 如何在 .cs 类而不是 Blazor 页面中使用 Blazored.LocalStorage?
- angular - Angular 单元测试用例随机失败
- ios - 世界跟踪性能受到资源限制的影响
- azure - 安装多个版本的模块时的Powershell #Requires 语句
- bokeh - BokehJS 库缺少错误且没有绘图
- javascript - 我试图在 JS 中创建一个数组,然后循环遍历它