python - Django 模型 : Default for Choice Foreign Key

标签 python django django-models

我有一个 Type 模型类,如下所示:

class Type(models.Model):
    ENVIRONMENT = 'A'
    HUMANENV = 'B'
    HUMAN = 'C'
    ANIMAL = 'D'
    UNKNOWN = 'H'
    TYPE_CHOICES = [
        (ENVIRONMENT, 'Environment'),
        (HUMANENV, "Human-related Environment"),
        (HUMAN, 'Human'),
        (ANIMAL, 'Animal'),
        (UNKNOWN, 'Unknown'),
    ]
    code = models.CharField(max_length=1, choices=TYPE_CHOICES, unique=True)

    class Meta:
        ordering = ['code']

    def __str__(self):
        return self.get_code_display()

另一个示例模型,其中一个字段是类型模型的外键,如下所示:

class Sample(models.Model):
    sample_id = models.CharField(max_length=20, unique=True)
    type = models.ForeignKey("Type", on_delete=models.CASCADE, blank=True, default=get_default_type())

    class Meta:
        ordering = ["sample_id"]

    def __str__(self):
        return self.sample_id

其中 get_default_type 是一个返回默认 Type 模型实例的 pk 的函数:

def get_default_type():
    return Type.objects.get(code="H").id

问题是当我运行 Sample.objects.create(sample_id="some_id") 时,它给了我错误

IntegrityError: null value in column "type_id" violates not-null constraint
DETAIL:  Failing row contains (28113, some_id, null).

正如您在错误消息的第二行中看到的,type_id 为 null,而不是 get_default_type 函数返回的 pk。

我尝试为外键设置 null=True ,当我这样做时,我能够创建 Sample 模型实例,但使用 None 类型而不是我想要的 Unknown 类型。我该如何解决这个问题?

最佳答案

两种解决方案:

覆盖管理器

从此response您可以在管理器中使用 get_by_natural_key

managers.py

from django.db import models
class TypeManager(models.Manager):
    """Enable fixtures using self.sigla instead of `id`"""

    def get_by_natural_key(self, code):
        return self.get(code=code)
class Type(models.Model):
    #.... Declare your model here
    objects = Type()

或者...

改变你的PK!

class Type(models.Model):
    #.... Declare your model here
    code = models.CharField(max_length=1, choices=TYPE_CHOICES, unique=True, primary_key=True)

无论哪种方式,在您的相关模型声明中:

class Sample(models.Model):
    type = models.ForeignKey("Type", on_delete=models.CASCADE, blank=True, default='H')

    class Meta:
        ordering = ["sample_id"]

    def __str__(self):
        return self.sample_id

附注:请注意类型。 它是 protected 关键字,不应使用。

关于python - Django 模型 : Default for Choice Foreign Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58476249/

相关文章:

python - Selenium 不会加载完整的 DOM 树,只会加载页面源代码

python - 使用自写函数将Python列表中的值上传到MySql

python - Django 和 urls.py : How do I HttpResponseRedirect via a named url?

django - 我们可以在 django 的单个 html 模板中扩展多个 html 吗?如果是,那么如何?

python - 是否需要在模型字段中设置 max_length?

python - MySQL 在 "Unknown column ' 中给出了 'field list' user.id' 错误使用 Django 的自动 id

python - 使用 urllib2 执行 URL 并返回渲染的 HTML 输出,而不是 HTML 本身

Python文件打开功能模式

python - 如何从 Django URL 更改语言?

Django 根据条件对相关对象进行计数