10

Say I have a Person model:

class Person(models.Model):
    name = models.CharField(max_length=50)

    email = models.EmailField()
    telephone = models.CharField(max_length=50)

For every Person I want to ensure that there is contact information. I don't need both email and telephone (though both is okay) but I need to ensure that at least one is provided.

I know I can check this stuff in forms, but is there a way I can do this at Model/database level to save repeating myself?

Oli
  • 235,628
  • 64
  • 220
  • 299

1 Answers1

27

Write a clean method for your model.

from django.core.exceptions import ValidationError


class Person(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()
    telephone = models.CharField(max_length=50)

    def clean(self):
        if not (self.email or self.telephone):
            raise ValidationError("You must specify either email or telephone")

If you use a model form (e.g. in the Django admin), Django will call the clean method for you. Alteratively, if you are using the ORM directly, you can call the full_clean() method on the instance manually.

Alasdair
  • 298,606
  • 55
  • 578
  • 516