我有一个 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/