[Fixed]-Specific way of requiring one of two fields in django model definition

14👍

As commented use clean

class MyModel(models.Model):
    field1 = models.TextField(blank=True)
    field2 = models.TextField(blank=True)

    def clean(self):
        cleaned_data = super().clean()
        if not cleaned_data.get('field1') and not cleaned_data.get('field2'):  # This will check for None or Empty
            raise ValidationError({'field1': 'Even one of field1 or field2 should have a value.'})
👤Serjik

33👍

This is an old question, but since this was the first hit for me when I searched for "django model field require one of two", I should point out that while overriding clean() may have been a good practise 3 years ago, Django’s support for database constraint definitions in the Meta class is a much better choice for this these days. This tutorial put me on the right path, but here’s a code sample from our model:

class MyModel:

    thing1 = models.PositiveIntegerField(null=True)
    thing2 = models.PositiveIntegerField(null=True)

    class Meta:
        constraints = [
            models.CheckConstraint(
                name="%(app_label)s_%(class)s_thing1_or_thing2",
                check=(
                    models.Q(thing1__isnull=True, thing2__isnull=False)
                    | models.Q(thing1__isnull=False, thing2__isnull=True)
                ),
            )
        ]

Leave a comment