I have a model with a non-nullable CharField
and 2 x nullable CharField
:
class MyModel(models.Model):
name = models.CharField('Name', max_length=255, null=False)
title = models.CharField('Title', max_length=255, blank=True)
position = models.CharField('Position', max_length=255, blank=True)
I want to ensure that name
, title
, and position
are unique together, and so use a UniqueConstraint
:
def Meta:
constraints = [
models.UniqueConstraint(
fields=['name', 'title', 'position'],
name="unique_name_title_position"
),
]
However, if title
is None
then this constraint fails.
Looking into why, this is because you can insert NULL
values into columns with the UNIQUE
constraint because NULL
is the absence of a value, so it is never equal to other NULL
values and not considered a duplicate value. This means that it's possible to insert rows that appear to be duplicates if one of the values is NULL
.
What's the correct way to strictly enforce this uniqueness in Django?