我有两个应用程序: collection
和 accounts
,两者都定义了模型。我正在导入模型 ReporterProfile
从 accounts
到 collection
。同样,我正在导入一个模型 Report
从 collection
到 accounts
。
来自 --- 的 Report
模型在 collection
accounts
模型类方法中被调用,如下所示:
from collection.models import Report
class ReporterProfile(models.Model):
....
def published_articles_number(self):
num = Report.objects.filter(reporterprofile=self.id).count()
return num
Similarly, I am importing ReporterProfile
and User
models from accounts
to collection
model like this:
from accounts.models import ReporterProfile, User
from <project_name> import settings
class Report(models.Model):
reporterprofile = models.ForeignKey(ReporterProfile, on_delete=models.CASCADE, verbose_name="Report Author")
...
class Comment(models.Model):
report = models.ForeignKey(Report, on_delete=models.CASCADE, related_name='comments')
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name="Comment by")
...
运行服务器或 makemigrations 时,出现错误:
File "F:\project_name\accounts\models.py", line 8, in <module>
from collection.models import Report
File "F:\project_name\collection\models.py", line 2, in <module>
from accounts.models import ReporterProfile, User
ImportError: cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import) (F:\project_name\accounts\models.py)
我认为错误是由于错误的导入模式造成的。我应该怎么办?
原文由 forest 发布,翻译遵循 CC BY-SA 4.0 许可协议
对于
ForeignKey
:您可以使用 --- 而不是使用
reporterprofile = models.ForeignKey(ReporterProfile, ...)
reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...)
,因此您不必导入模型。为了防止循环导入错误:
而不是使用:
您可以使用: