[Solved]-Django unique=True except for blank values

4👍

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.

👤SaeX

3👍

Django supports creating unique constraints that have conditions. A custom constraint can be created that enforces uniqueness for a given field only under the condition that a field’s value is not blank.

from django.db.models import Q

serialnumber_is_not_blank = ~Q(serial_number="")

class Meta:
   constraints = [
        models.UniqueConstraint(
            fields=["serial_number"],
            condition=serialnumber_is_not_blank,
            name="unique_serial_number",
        )
    ]
👤jnns

-1👍

I’m pretty sure that having null values aren’t taken into account in uniqueness constraints. The way to get around this is to not use null, but instead use an empty string. So, remove null=True.

Leave a comment