Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django unique=True except for blank values

Tags:

python

django

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 blank and null because all parts don't necessarily have a serial number. However, after storing one part without a serial number, blank is no longer unique and I get this error:

Part with this Serial number already exists.

Is there a workaround for this? I already looked at this question, but I don't have a modelform. I either use the admin or do it directly in the code.

like image 466
jdickson Avatar asked Mar 21 '12 15:03

jdickson


1 Answers

I came across the same issue and fixed it by specifying None for the field when saving.

Specifying default=None could be helpful as well.

like image 197
SaeX Avatar answered Oct 22 '22 01:10

SaeX