Django one of 2 fields must not be null

Since Django 2.2, you can use the built-in constraints feature in Django. No need for 3rd party code.


Model.clean

One normally writes such tests in Model.clean [Django-doc]:

from django.core.exceptions import ValidationError

class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    field1= models.IntegerField(null=True)
    field2 = models.IntegerField(null=True)

    def clean(self):
        super().clean()
        if self.field1 is None and self.field2 is None:
            raise ValidationError('Field1 or field2 are both None')

Note that this clean method is not validated by default when you .save() a model. It is typically only called by ModelForms built on top of this model. You can patch the .save() method for example like here to enforce validation when you .save() the model instance, but still there are ways to circumvent this through the ORM.

django-db-constraints (not supported by some databases)

If your database supports it (for example MySQL simply ignores the CHECK constraints), SQL offers a syntax to add extra constraints, and a Django package django-db-constraints [GitHub] provides some tooling to specify such constraints, like:

class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    field1= models.IntegerField(null=True)
    field2 = models.IntegerField(null=True)

    class Meta:
        db_constraints = {
            'field_null': 'CHECK (field1 IS NOT NULL OR field2 IS NOT NULL)',
        }

Update: Django constraint framework

Since django-2.2, you can make use of the Django constraint framework [Django-doc]. With this framework, you can specify database constraints that are, given the database supports this, validated at database side. You thus can check if at least one of the two fields is not NULL with a CheckConstraint [Django-doc]:

class Person(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    field1= models.IntegerField(null=True)
    field2 = models.IntegerField(null=True)

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(field1__isnull=False) | Q(field2__isnull=False),
                name='not_both_null'
            )
        ]

You can use Model.clean() method:

def clean(self):
    if self.field1 is None and self.field2 is None:
        raise ValidationError(_('field1 or field2 should not be null'))

See https://docs.djangoproject.com/en/2.1/ref/models/instances/#django.db.models.Model.clean