我有两个名为 collection
的应用程序, accounts
.这两个应用程序都定义了模型。我正在导入模型 ReporterProfile
来自 accounts
应用到 collection
.同样,模型 Report
来自应用程序 collection
至accounts
.Report
型号来自 collection
app 在 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
同样,我正在导入
ReporterProfile
和 User
来自 accounts
的型号应用到 collection
像这样的应用模型: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 时,出现错误:
文件“F:\project_name\accounts\models.py”,第 8 行,在
从 collection.models 导入报告
文件“F:\project_name\collection\models.py”,第 2 行,在
从accounts.models 导入ReporterProfile,用户
ImportError:无法从部分初始化的模块“accounts.models”导入名称“ReporterProfile”(很可能是由于循环导入)(F:\project_name\accounts\models.py)
我认为错误是由于错误的导入模式而出现的。我该怎么办?
最佳答案
对于 ForeignKey
:
而不是使用 reporterprofile = models.ForeignKey(ReporterProfile, ...)
, 你可以使用 reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...)
,因此您不必导入模型。
为了防止循环导入错误:
而不是使用:
from accounts.models import ReporterProfile
[...]
foo = ReporterProfile()
您可以使用:
import accounts.models
[...]
foo = accounts.models.ReporterProfile()
关于python - Django 导入错误 : cannot import name 'ReporterProfile' from partially initialized module 'accounts.models' (most likely due to a circular import),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62100550/