Enforcing only one True value in BooleanField via CheckConstraint

Hi everyone

I have a field (let’s call it, “chairman”).

chairman = models.BooleanField(default=False)

I am trying to create a CheckConstraint that triggers when a user attempts to create more than one chairman. Hence, there can be only one True in the chairman column. How do I phrase the condition for CheckConstraint?

You can do this with a UniqueConstraint:

class Person(models.Model):
    name = models.CharField()
    chairman = models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['chairman'],
                condition=models.Q(chairman=True),
                name='unique_chairman'
            )
        ]

This will raise an IntegrityError if more than one row is attempted to be saved with a True value.

For a running example, see this DryORM snippet: DryORM - Django ORM Playground

Thank you so much.

Actually the above table exemplifies my dilemma more accurately. There can be only one chairman for each host.

The table could be:

class Event(models.Model): 
    host = models.ForeignKey(
        Host,
        on_delete=models.CASCADE,
    )
    invitee = models.CharField(max_length=50, unique=True)
    chairman =  models.BooleanField(default=False)

That is a different question that would have been useful in your first post :wink:

You can achieve this by changing which field is considered unique for the condition:

class Event(models.Model): 
    host = models.ForeignKey(
        Host,
        on_delete=models.CASCADE,
    )
    invitee = models.CharField(max_length=50, unique=True)
    chairman =  models.BooleanField(default=False)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['host'],
                condition=models.Q(chairman=True),
                name='unique_chairman_per_host'
            )
        ]

This ensures the host column is unique across all rows where chairman=True.