在Django中验证值列表

4 投票
2 回答
3324 浏览
提问于 2025-04-16 20:31

在我的模型中,有一个字段应该只包含'A'、'B'和'C'这几个值。这样的话,使用choice参数来声明这个字段是不是最好的选择呢?

如果我不打算使用choice参数,而是想写一些自定义的验证逻辑,那我应该在哪里写呢?是放在模型的clean方法里吗?我还看到过clean_<fieldname>这种方法——这些方法是干什么用的,还是说它们只适用于表单?我想在模型里做这个验证,因为我没有使用表单。

class Action(models.Model):
    """
    Contains the logic for the visit
    """
    id = models.AutoField(primary_key=True)
    path = models.CharField(max_length=65535, null=False)
    to = models.IntegerField(null=False)

    def clean(self, **kwargs):
        """
        Custom clean method to do some validation
        """
        #Ensure that the 'to' is either 1,2 or 3.
        if self.to not in [0, 1, 2]:
            raise ValidationError("Invalid to value.")

在进行验证的时候,我需要返回一些值吗?当有人创建新记录时,我的方法会被调用吗?

(虽然我看过文档,但还是有点困惑。)

非常感谢!

2 个回答

2

如果你只想让它的值是'A'、'B'和'C',那么你绝对应该使用Django自带的验证功能,而不是自己去写一个。你可以查看这个链接:https://docs.djangoproject.com/en/1.3/ref/models/fields/,里面有一个叫choices的部分。

简单来说:

class Action(models.Model):
    """
    Contains the logic for the visit
    """

    TO_CHOICES = (
        (0, 'Choice 0'),
        (1, 'Choice 1'),
        (2, 'Choice 2'),
    )
    id = models.AutoField(primary_key=True)
    path = models.CharField(max_length=65535, null=False)
    to = models.IntegerField(null=False, choices=TO_CHOICES)
1

在你给的例子中,我会使用 choice 参数。如果你把对 to 字段的验证放在清理方法里,那么任何错误都会和动作实例关联,而不是和 to 字段关联。

正如你所说,clean_<fieldname> 方法是用来处理表单字段的。在模型中,你可以定义一些验证器

下面是你清理方法的一个例子,改写成验证器的样子。

from django.core.exceptions import ValidationError

def validate_to(value):
    """
    Ensure that the 'to' is either 1, 2 or 3.
    """
    if value not in [1, 2, 3]:
        raise ValidationError("Invalid 'to' value.")

class Action(models.Model):
    """
    Contains the logic for the visit
    """
    id = models.AutoField(primary_key=True)
    path = models.CharField(max_length=65535, null=False)
    to = models.IntegerField(null=False,validators=[validate_to])

撰写回答