djangovalidationdjango-modelscheck-constraints

Model field "null together or not at all" constraint


I need a way to create either a validator or a constraint at model level to evaluate two or more fields to be able to be null/blank only if all of them are null/blank at the same time.

For example, in the next model:

from django.db import models

class Example(models.Model):
    A = models.CharField(max_length=16, blank=True)
    B = models.DateField(null=True, blank=True)
    C = models.FileField(upload_to='/', null=True)

If I try to create a new Example with either B or C values empty it should raise a ValidationError; but if both of them are empty it should be OK.


Solution

  • You can use a CheckConstraint:

    from django.db.models import CheckConstraint, Q
    
    class Example(models.Model):
        ...
        class Meta:
            constraints = [
                CheckConstraint(
                    check=(
                        (Q(B__isnull=True) & Q(C__isnull=True))
                        | Q(B__isnull=False) | Q(C__isnull=False)
                    ),
                    name="b_c_null_check",
                )
            ]