Lewis
Lewis

Reputation: 2798

Django: Vacate unique name if field is a particular value

What I want

I want a field to be unique unless a other field in a the same model is a particular value. Allowing me to vacate this unique name to a future model instance.

I also need to allow testname to be null encase there is no testname for that given test.

Unique Field: testname

Conditioner: cancelled=True

models.py (Simplified)

class Test(models.Model):
    testname = models.CharField(max_length=50, null=True, blank=True, unique=True)
    cancelled = models.BooleanField(default=False)

Upvotes: 0

Views: 20

Answers (1)

VisioN
VisioN

Reputation: 145428

You may use UniqueConstraint:

class Test(models.Model):
    testname = models.CharField(max_length=50, null=True, blank=True)
    cancelled = models.BooleanField(default=False)

    class Meta:
        constraints = (
            UniqueConstraint(fields=['testname'], condition=Q(cancelled=True), name='...'),
        )

This will add a constraint in your database table, making conditional uniqueness of the field. In this case, the form validation is not supported out of the box, so you need to add it separately.

Upvotes: 1

Related Questions