![](/img/trans.png)
[英]Python Django: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) (......)
[英]ImportError: cannot import name from partially initialized module Django
我遇到了一個我不知道為什么會發生錯誤的問題,請幫我解決這個錯誤:
錯誤:
ImportError: cannot import name 'User' from partially initialized module
'authentication.models' (most likely due to a circular import)
(/app/authentication/models.py)
用戶 model:
from projects.models import Organization
class User(AbstractBaseUser, PermissionsMixin):
organization = models.ForeignKey(Organization, on_delete=models.CASCADE, null=True)
此 ^ 導入后發生錯誤
項目型號:
from django.db import models
from authentication.models import User
class Organization(models.Model):
OWNER = 1
CONTRACTOR = 2
DISTRIBUTOR = 3
MANUFACTURER = 4
CONSULTANT = 5
ORG_TYPES = [
(OWNER, 'Owner'),
(CONTRACTOR, 'Contractor'),
(DISTRIBUTOR, 'Distributor'),
(MANUFACTURER, 'Manufacturer'),
(CONSULTANT, 'Consultant'),
]
name = models.CharField(max_length=255, default='')
created_at = models.DateTimeField(auto_now=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
is_active = models.IntegerField(default=1, null=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
org_type = models.CharField(max_length=1, choices=ORG_TYPES)
class Meta:
db_table = 'organizations'
class Project(models.Model):
name = models.CharField(max_length=255, default='')
description = models.CharField(max_length=255, default='')
created_at = models.DateTimeField(auto_now=True, null=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
is_active = models.IntegerField(default=1, null=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
account = models.ManyToManyField(User, related_name='account')
contractor = models.ForeignKey(Organization, related_name="contractor", on_delete=models.CASCADE)
distributor = models.ForeignKey(Organization, related_name="distributor", on_delete=models.CASCADE)
manufacturer = models.ForeignKey(Organization, related_name="manufacturer", on_delete=models.CASCADE)
consultant = models.ForeignKey(Organization, related_name="consultant", on_delete=models.CASCADE)
owner = models.ForeignKey(Organization, related_name="owner", on_delete=models.CASCADE)
class Meta:
db_table = 'projects'
這是因為您有兩個相互導入的模塊(這就是錯誤所說的意思:“很可能是由於循環導入”)
解決此問題的最簡單方法是將User
model 定義與Organization
定義放在同一文件中
這也很有意義,因為您的用戶似乎屬於一個組織
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.