我在django中得到一个循环导入错误,似乎无法解决它。这是我的models.py在affiliate(app)
from member.models import Member
class SubAffiliate(models.Model):
member_id = models.ForeignKey(Member, on_delete=models.CASCADE)
这是我的models.py在member(app)
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(
'member.Member',
on_delete=models.CASCADE
)
对于另一个models.py
文件,您也可以使用app_name.ModelName
:
# no import from affiliate.models
class Member(models.Model):
affiliates = models.ManyToManyField(
'affiliate.Affiliate',
blank=True,
related_name='members_affiliate'
)