Reputation: 121
New to django here. I want to compare two values from a model like the following inside an API made with django rest framework:
class SalaryRangeModel(models.Model):
salary_min = models.PositiveIntegerField
salary_max = models.PositiveIntegerField
I want to compare them. If salary_min is bigger than salary_max return a error.
Should I code this on the model? On the serializer? On the front-end?
Thanks!
Upvotes: 0
Views: 122
Reputation: 61
The best way to keep your database clean is to use a database constraint https://docs.djangoproject.com/en/dev/ref/models/constraints/#checkconstraint :
class SalaryRangeModel(models.Model):
salary_min = models.PositiveIntegerField
salary_max = models.PositiveIntegerField
class Meta:
constraints = [
models.CheckConstraint(
check=models.Q(salary_max__gt=models.F('salary_min')),
name='salary_max_bigger_than_salary_min'
),
]
Like all modifications to a model, you'll need to make a new migration.
Upvotes: 2