我在 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/