我想比较 django 模型中方法内的两个整数字段。 这两个字段未正确进行比较,并且引发错误 例如:
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
我试着简单地这样做:
def available_slots_left(self):
if self.allocated_slots < self.total_slots:
return True
return False
但它不起作用并返回此错误:
TypeError: '<=' not supported between instances of 'IntegerField' and 'int'
问题不在于你的方法,而在于你的验证器,特别是
MaxValueValidator(total_slots)
不起作用,因为 MaxValueValidator
需要传递一个 integer 而不是模型字段。如果您确实想为此设置一些验证,您可以为其创建一个 CheckConstraint:
from django.db import models
class YourModel(models.Model):
total_slots = models.IntegerField(default=0, help_text="Total number of vehicle slots available for allocation.")
allocated_slots = models.IntegerField(default=0, validators=[MinValueValidator(0)], )
class Meta:
constraints = [
models.CheckConstraint(
check=models.Q(allocated_slots__lte=models.F("total_slots")),
name="allocated_slots_lte_total_slots",
)
]