【问题标题】:ImportError: cannot import name from partially initialized module DjangoImportError:无法从部分初始化的模块 Django 中导入名称
【发布时间】:2022-01-24 13:39:11
【问题描述】:

我遇到了一个我不知道为什么会发生错误的问题,请帮我解决这个错误:

错误:

ImportError: cannot import name 'User' from partially initialized module 
'authentication.models' (most likely due to a circular import) 
(/app/authentication/models.py)

用户模型:

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'

【问题讨论】:

标签: python django


【解决方案1】:

这是因为您有两个相互导入的模块(这就是错误的含义:“很可能是由于循环导入”)

解决此问题的最简单方法是将User 模型定义与Organization 定义放在同一文件中

这也很有意义,因为您的用户似乎属于一个组织

【讨论】:

    猜你喜欢
    • 2020-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多