Django unique = True, except for empty values

I have this model:

class Part(models.Model): serial_number = models.CharField(max_length=15, null=True, blank=True, validators=[validate_serial], unique=True) .... 

serial_number can be empty and null because all parts do not necessarily have a serial number. However, after saving one part without the serial number, the empty string is no longer unique, and I get this error:

A part with this serial number already exists.

Is there a workaround for this? I have already addressed this issue , but I do not have a model. I either use the administrator or do it directly in the code.

+8
python django
source share
2 answers

I ran into the same problem and fixed it by specifying None for the field when saving.

Specifying default=None may also be useful.

+4
source share

I am pretty sure that with null values ​​are not taken into account in uniqueness constraints. A way around this is not to use zero, but instead use an empty string. So remove null=True .

-one
source share

All Articles