Which is better: using Django Constraints or raising a ValueError in the save method?
I’ve come across two ways to enforce a condition in Django models:
Using the
save
method with aValueError
:class MyModel(models.Model): field_name = models.CharField(max_length=100) def save(self, *args, **kwargs): if not self.field_name: # Example condition raise ValueError("Field name cannot be empty.") super().save(*args, **kwargs)
Using Django's Constraints (like
CheckConstraint
):from django.db import models from django.db.models import Q class MyModel(models.Model): field_name = models.CharField(max_length=100) class Meta: constraints = [ models.CheckConstraint( check=~Q(field_name=""), # Example condition name="field_name_not_empty", ) ]
I know both approaches can enforce conditions, but I’m wondering:
- Which approach is more efficient?
- Which one is generally better to use in real-world scenarios?
For short answer, in this case, I would use second option.
For longer answer:
Raise Exception Within Python:
Using the save method with a ValueError is checked within the python code, it can add overhead for each time save method is called and it wont evaluate inserted data.
But if you need to check more complex code which database engine cant handle or add custom exceptions, it is better to use first option.
Using CheckConstraint:
Using second option, evaluation is done by database engine, what is more efficient that python and it also can validate inserted data. In this case it would be better to use db engine to validate, to also check insert data and keep it closer to source. If check is simple enought for database engine, use CheckConstraint method.