I want to compare two integer fields inside a method in a django model. The two fields are not correctly getting compared and it is throwing an error for example:
total_slots = models.IntegerField(default=0, help_text="Total number of vehicle slots available for allocation.")
allocated_slots = models.IntegerField(default=0,
validators=[
MaxValueValidator(total_slots),
MinValueValidator(0)
], )
def available_slots_left(self):
if self.allocated_slots < self.total_slots:
return True
return False
I tried to just simply do this:
def available_slots_left(self):
if self.allocated_slots < self.total_slots:
return True
return False
but it didn't work and it returned this error:
TypeError: '<=' not supported between instances of 'IntegerField' and 'int'
The problem is not in your method but rather your validator, specifically
MaxValueValidator(total_slots)won't work becauseMaxValueValidatorneeds to be passed an integer and not a model field. If you do want to set up some validation for that you can create a CheckConstraint for it: