【问题标题】:How to create choice field in django model using another model如何使用另一个模型在 django 模型中创建选择字段
【发布时间】:2021-01-25 07:52:39
【问题描述】:

我有两个模型,第一个是用户模型,第二个是组织模型。 管理员将负责在组织模型中添加数据。所以我使用了外键。

class Organizaton(models.Model):
    name = models.CharField(max_length=255)
    status = models.BooleanField(default=True)
    created_by = models.ForeignKey(CustomUser,on_delete=models.CASCADE,limit_choices_to=    {'is_staff': True})
    created_date = models.DateTimeField(auto_now_add=True)

我有一个自定义用户表,我想在其中存储哪个用户属于哪个组织:

class CustomUser(AbstractUser): 

    organization_name = models.ForeignKey(Organization,on_delete = models.CASCADE)

如果我先声明CustomUser类,那么里面就有错误 显示 class Organization is not Found or declared 的 organization_name 字段中的 CustomUser 类。

如果我在 CustomUser 模型类之前声明组织模型类,那么我会在 created_by 字段中的组织类中收到一个错误,即 CustomUser class not found or declared。

我该如何解决这个问题?

【问题讨论】:

    标签: django django-models


    【解决方案1】:

    首先声明您的CustomUser,然后将您的ForeignKey 更改为如下字符串:

    class CustomUser(AbstractUser): 
    
        organization_name = models.ForeignKey('Organization', on_delete=models.CASCADE)
    

    并且不再依赖于申报顺序。

    【讨论】:

      【解决方案2】:

      你写过吗 AUTH_USER_MODEL = app_name.CustomUser 在你的设置文件中?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-14
        • 2018-04-15
        • 1970-01-01
        • 2020-10-06
        相关资源
        最近更新 更多