python - 来自不同应用程序的导入错误

标签 python django

我正在从不同的应用程序导入模型,但收到此错误,并且我不确定为什么会发生这种情况。

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 - 来自不同应用程序的导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28787410/

相关文章:

python - 如何编写一个安装脚本,将除 Django 应用程序之外的所有内容复制到 dist-packages 中?

python - Pandas 在与正则表达式匹配的列中用零替换负值

python - 让python 3代码在telnetlib超时后继续

python - 为什么我的字计数器输出行 ` 1` ?

Django - 如何显示保存在 ImageField 中的照片?

python - Django 测试 - 更新 View 不​​会更改数据库对象字段

python - python hmmlearn 中导入错误

python - 如何在 Python 中访问 OpenCV HoughCircles 结果?

python manage.py dumpdata 无法序列化数据库

Django extra javascript 在子页面中不起作用