python - 循环依赖导致 ImportError : cannot import name

标签 python django model circular-dependency

我还是第一次遇到这种情况。也许这是由于糟糕的设计。无论如何,我不知道如何解决它。以下是表现不佳的模型:

talk/models.py

from agencies.models import UserProfile
class Message(models.Model):
    text = models.TextField()
    source = models.ForeignKey(UserProfile, related_name='source')
    dest = models.ForeignKey(UserProfile, related_name='dest')

    created = models.DateTimeField(auto_now_add=True)
    seen = models.BooleanField(default=False)

    class Meta:
        ordering = ['created']

机构/models.py

# from talk.models import Message

当我取消注释时,它显示ImportError:无法导入名称UserProfile。我真的很想要它,所以我可以将此属性添加到我的 UserProfile 类中...

class UserProfile(models.Model):
        # ...
        @property
        def unseen_messages_from(self):
            pass # :(

关于如何解决此问题有什么想法吗?

最佳答案

Django 外键允许您将模型指定为字符串以避免导入问题。根据您的情况,您可以这样做:

class Message(models.Model):
    text = models.TextField()
    source = models.ForeignKey('<appname>.UserProfile', related_name='source')
    dest = models.ForeignKey('<appname>.UserProfile', related_name='dest')

    created = models.DateTimeField(auto_now_add=True)
    seen = models.BooleanField(default=False)

    class Meta:
        ordering = ['created']

即,您可以一起删除导入。

引用号,documentation

关于python - 循环依赖导致 ImportError : cannot import name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24769423/

相关文章:

python - 在数据透视表中使用相同的值和列名

ruby-on-rails - Geokit 和 Authlogic,在创建用户时对用户 ip 地址进行地理编码

python - 使用 Docker 实例制作 Web 服务器 - 什么去哪里?

python - Windows 与 Python Hook

python - Django 自定义查询集过滤器

python - 在 Django 2 中使用 URLPathVersioning 处理版本控制

python - 如何让非员工用户访问 Django 管理站点?

asp.net-mvc - 模型中名为 Title 的属性与 View 中名为 View.Title 的属性之间的绑定(bind)冲突(在 MVC 中)

python - Tensorflow:如何将卡住模型转换为保存模型

python ftplib 和 TLS,数据连接问题