我正在从不同的应用程序导入模型,但出现此错误,我不确定为什么会发生这种情况。
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 354, in execute
django.setup()
File "/Library/Python/2.7/site-packages/django/__init__.py", line 21, in setup
apps.populate(settings.INSTALLED_APPS)
File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 108, in populate
app_config.import_models(all_models)
File "/Library/Python/2.7/site-packages/django/apps/config.py", line 202, in import_models
self.models_module = import_module(models_module_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/bli1/Development/Django/Spark/users/models.py", line 5, in <module>
from notifications.models import Notification
File "/Users/bli1/Development/Django/Spark/notifications/models.py", line 2, in <module>
from users.models import UserProfile
ImportError: cannot import name UserProfile
我的通知/型号:
from django.db import models
from users.models import UserProfile
from restaurants.models import Restaurant
class Notification(models.Model):
user = models.ForeignKey(UserProfile)
name = models.CharField(max_length=100)
about = models.TextField(max_length=1024, blank=True)
restaurant = models.ForeignKey(Restaurant)
def __str__(self):
return self.name
我的用户/models.py:
from django.db import models
from django.contrib.auth.models import User
from notifications.models import Notification
class UserProfile(models.Model):
user = models.OneToOneField(User)
bio = models.TextField(max_length=1024, null=True, blank=True)
最佳答案
您是循环导入依赖项的受害者。为了解决这个问题,您需要在ForeignKey
中告诉Django模型的导入路径,而不是实际导入它:
class Notification(models.Model):
user = models.ForeignKey('users.UserProfile')
另外,不要忘记从Notifications / models.py中的
from users.models import UserProfile
中删除导入语句。关于python - 来自不同应用程序的ImportError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28787410/