I'm not sure about MySQL, but SQLite and PostgreSQL do not consider NULL
values to be equal, so the behavior you are looking for is actually the default.
You can verify this yourself:
class MyModel(models.Model):
title = models.CharField(unique=True, null=True, max_length=255)
>>> MyModel.objects.create()
<MyModel: MyModel object (1)>
>>> MyModel.objects.create()
<MyModel: MyModel object (2)>
For a unique_together
:
class MyModel(models.Model):
title = models.CharField(null=True, max_length=255)
description = models.CharField(null=True, max_length=255)
class Meta:
unique_together = (('title', 'description'),)
>>> MyModel.objects.create(title='x')
<MyModel: MyModel object (1)>
>>> MyModel.objects.create(title='x')
<MyModel: MyModel object (2)>
Note that in the second example, there is no unique constraint on the title
field, only the unique together on both fields.