'Compare two numbers from django rest framework model
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!
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gabrielley68 |
