如何在Django模型方法中比较两个整数字段?

0 投票
2 回答
40 浏览
提问于 2025-04-12 16:01

我想在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'

2 个回答

2

你的错误出现在MaxValueValidator这个验证器上,这个验证器只接受整数,但在你的情况下,你传入了一个模型字段。你可以用几种方法来实现这个验证。

在你的模型中添加这个方法:

def save(self, *args, **kwargs):
    if self.allocated_slots > self.total_slots:
        raise ValidationError("Your error message")
    return super().save(*args, **kwargs)

你可以使用这个简单的方法,不过在保存之前,你需要先调用一下full_clean()这个方法。

def clean(self, *args, **kwargs):
    if self.allocated_slots > self.total_slots:
        raise ValidationError("Your error message")
2

问题出在你的验证器上,而不是你的方法。具体来说,MaxValueValidator(total_slots) 这个验证器是不能正常工作的,因为 MaxValueValidator 需要一个整数作为参数,而不是一个模型字段。如果你想为这个设置一些验证,可以创建一个 检查约束

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",
            )
        ]

撰写回答