I have a Type model class as follows:
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()
And another Sample model where one of the fields is a foreign key to the Type model as follows:
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
where get_default_type is a function that returns the pk for the default Type model instance:
def get_default_type():
return Type.objects.get(code="H").id
The problem is when I run Sample.objects.create(sample_id="some_id"), it is giving me the error
IntegrityError: null value in column "type_id" violates not-null constraint
DETAIL: Failing row contains (28113, some_id, null).
As you can see in the second line of the error message, the type_id is null instead of the pk as returned by the get_default_type function.
I have tried setting null=True for the foreign key and when I do that I am able to create the Sample model instance, but with a None type instead of the Unknown type as I wanted. How can I fix this?