Django ImportError:无法从部分初始化的模块“ accounts.models”中导入名称“ ReporterProfile”(很可能是由于循环导入)

时间:2020-05-30 09:34:35

标签: python django django-models

我有两个名为collectionaccounts的应用程序。这两个应用程序都定义了模型。我正在将模型ReporterProfileaccounts应用导入到collection。同样,从应用Reportcollection的模型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

类似地,我将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)

我认为错误是由于导入模式错误而引起的。我该怎么办?

2 个答案:

答案 0 :(得分:5)

对于ForeignKey

您可以使用reporterprofile = models.ForeignKey(ReporterProfile, ...)而不是使用reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...),因此不必导入模型。

为防止循环器导入错误:

而不是使用:

from accounts.models import ReporterProfile
[...]
foo = ReporterProfile()

您可以使用:

import accounts.models
[...]
foo = accounts.models.ReporterProfile()

答案 1 :(得分:0)

确保您正在编写 create models nane,因为我遇到了同样的问题,当查看我的导入时,我编写了 userFormdata 而不是 userformData(我将 'f' 大写)

#wrong inport 
from users_handler.models import userFormData
#Correct import 
from users_handler.models import userformData