I have a model similar to this one:
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)
At least one of the fields field1
or field2
must not be null. How I can I verify it in the model?
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 ModelForm
s 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'
)
]
所有评论(0)