for*_*est 6 python django django-models
我有两个名为collection, 的应用程序accounts。这两个应用程序都定义了模型。我正在将模型ReporterProfile从accounts应用程序导入到collection. 同样,Report从应用程序collection到accounts.
Report来自collectionapp的模型在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
Run Code Online (Sandbox Code Playgroud)
同样,我进口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")
...
Run Code Online (Sandbox Code Playgroud)
运行服务器或 makemigrations 时,出现错误:
文件“F:\project_name\accounts\models.py”,第 8 行,来自 collection.models 导入报告
文件“F:\project_name\collection\models.py”,第 2 行,在 from accounts.models import ReporterProfile, User
导入错误:无法从部分初始化的模块“accounts.models”中导入名称“ReporterProfile”(很可能是由于循环导入)(F:\project_name\accounts\models.py)
我认为错误是由于错误的导入模式而出现的。我该怎么办?
Blu*_*sky 17
对于ForeignKey:
reporterprofile = models.ForeignKey(ReporterProfile, ...)您可以使用reporterprofile = models.ForeignKey("accounts.ReporterProfile", ...),而不是使用,因此您不必导入模型。
为了防止循环导入错误:
而不是使用:
from accounts.models import ReporterProfile
[...]
foo = ReporterProfile()
Run Code Online (Sandbox Code Playgroud)
您可以使用:
import accounts.models
[...]
foo = accounts.models.ReporterProfile()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13232 次 |
| 最近记录: |