django

Django uniqueness constraint when a specific field is True


I've got a Django model like this:

class Process(Place):
    isRunning = models.BooleanField(default=True)
    name      = models.CharField(max_length=20)

I'd like to enforce that the name field is unique when isRunning is true.

Is this constraint possible in in Django models?


This might be a duplicate of this question, but it doesn't have an accepted answer, and Django has developed a lot since it was asked.


Solution

  • If your database supports it you could set up a partial unique index.

    A partial index is an index built over a subset of a table; the subset is defined by a conditional expression (called the predicate of the partial index). The index contains entries only for those table rows that satisfy the predicate.

    Starting with version 2.2 you can simply declare the partial unique index in your model:

    from django.db.models import Q, UniqueConstraint
    
    class Process(Place):
        ...
        class Meta:
            constraints = [UniqueConstraint(fields=["name"], condition=Q(isRunning=True))]
    

    Below version 2.2 there's no special Django support for this, but you can set it up in a data migration (see here for more details).

    In your case it would look something like:

    operations = [
        migrations.RunSQL("CREATE UNIQUE INDEX running_name ON app_process(isRunning, name)
                           WHERE isRunning"),
    ]