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

标签 python django django-models

我有两个名为 collection 的应用程序, accounts .这两个应用程序都定义了模型。我正在导入模型 ReporterProfile来自 accounts应用到 collection .同样,模型 Report来自应用程序 collectionaccounts .
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

同样,我正在导入 ReporterProfileUser来自 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/

相关文章:

python - 从 CSV 文件数据动态创建列表列表

django - 我正在尝试使用 django-mptt 构建网站导航

python - 尽管在设置中指定了日期格式,但运行测试时 Django 仍给出 "invalid date format"错误

python - python3中的ssl证书和https连接

python - Pandas 根据分组列值合并 DF 列表

python - 在基于 Django 类的 View 中传递查询参数

django select_related - 何时使用它

python - 在 Django Admin 中更新表关系

python - 在 Social-App-Django 中扩展用户模型或自定义管道

javascript - 使用 Javascript 和 Django 模板动态加载 HTML 图像