class Item(Model):
name = models.CharField(max_length=200, null=False)
unit = models.CharField(max_length=20, null=True)
owner = models.CharField(max_length=200, null=True)
class Meta:
constraints = [
models.UniqueConstraint(
name='%(app_label)s_%(class)s_name_unit_owner_uniq',
fields=('name', 'unit', 'owner')
),
]
Unfortunately I wasn't achieving what I wanted. In that simple example a user could create duplicated records for unit = None. Also, It is possible to create duplicated records where .This behavior conforms the SQL standards, of course.
In this article I explain how I have done to get the wanted behavior and the reasons that it might be cumbersome in some cases. In the same article I show an SQL expression that is clean and should result in a way more DRY code in model declaration. The SQL expression is:
CREATE UNIQUE INDEX core_item_name_unit_owner_uniq
ON public.core_item (name, COALESCE(owner,"-"), COALESCE(unit,"-"));