验证Django中的值列表

时间:2011-06-29 13:27:08

标签: python django django-models

在我的模型中,我有一个字段,其中只应包含值'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 个答案:

答案 0 :(得分:2)

如果你只想要它是'A','B'和'C',你绝对应该使用Django内置的验证而不是自己动手。请参阅标题为choices

的部分中的https://docs.djangoproject.com/en/1.3/ref/models/fields/

简而言之:

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 :(得分:1)

在您给出的示例中,我将使用choice参数。如果您将to字段的验证放在clean方法中,那么任何错误都将与操作实例相关联,而不是to字段。

正如您所说,clean_<fieldname>方法适用于表单字段。在模型上,您可以定义validators

以下是您将clean方法重写为验证程序的示例。

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