python - 导入错误: cannot import name 'Affiliate' from partially initialized module 'affiliate.models' (most likely due to a circular import)

标签 python django django-models

我在 django 中遇到循环导入错误,并且似乎无法解决它。 这是我在affiliate(app)中的models.py

from member.models import Member

class SubAffiliate(models.Model):
    member_id = models.ForeignKey(Member, on_delete=models.CASCADE)

这是我在 member(app) 中的 models.py

from affiliate.models import Affiliate

class Member(models.Model):
    affiliates = models.ManyToManyField(Affiliate, blank=True, related_name="members_affiliate")

为了解决问题,我尝试像这样导入

import affiliate.models

然后像这样使用它

affiliate.models.Affiliate

然后我收到此错误 AttributeError: module 'affiliate' has no attribute 'models'

我应该怎么做才能解决这个错误。谢谢!

最佳答案

两个模型不能互相导入。如果您需要引用另一个模块的模型,您可以使用字符串文字:

# no import from member.models!

class SubAffiliate(models.Model):
    member = models.ForeignKey(
        <strong>'member.Member'</strong>,
        on_delete=models.CASCADE
    )

对于其他 models.py 文件,您还可以使用带有 app_name.ModelName 的字符串:

# no import from affiliate.models

class Member(models.Model):
    affiliates = models.ManyToManyField(
        <strong>'affiliate.Affiliate'</strong>,
        blank=True,
        related_name='members_affiliate'
    )

关于python - 导入错误: cannot import name 'Affiliate' from partially initialized module 'affiliate.models' (most likely due to a circular import),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69700216/

相关文章:

python - 如何将搜索匹配 *.txt 的文件的输出保存到变量中?

django - Django SelectMultiple 小部件的动态选择

python - 如何在Django中手动定义遗留数据库的一对一键

Django Queryset - 通过 model.choices 获取计数

python - Kivy 侧边栏加上内容布局

python - 如何加速用 python 编写的 couchdb View

python - Django - 表单 - (?P<pk>\d+)/$ 表示什么?

html - Django - CSS 文件未正确链接到模板

python - Django prefetch_related 从具有多个多对多关系的模型

python - 使用字符串和整数对列表进行排序