7

我有一个使用CompareDates为我的模型验证器调用的验证类的模型,我想向验证器传递两个字段值。但是我不确定如何在验证器中使用多个字段值。

我希望能够在日期之间进行比较,以便整体验证模型,但您似乎无法对传递给验证器的值进行关键字,或者我错过了什么?

from django.db import models
from myapp.models.validators.validatedates import CompareDates

class GetDates(models.Model):
    """
    Model stores two dates
    """
    date1 = models.DateField(
            validators = [CompareDates().validate])
    date2 = models.DateField(
            validators = [CompareDates().validate])
4

1 回答 1

7

“正常”验证器只会获取当前字段值。所以它不会做你想做的事。但是,您可以添加一个干净的方法,并且 - 如果需要的话 - 像这样覆盖您的保存方法:

class GetDates(models.Model):
    date1 = models.DateField(validators = [CompareDates().validate])
    date2 = models.DateField(validators = [CompareDates().validate])
    def clean(self,*args,**kwargs):
        CompareDates().validate(self.date1,self.date2)
    def save(self,*args,**kwargs):
        # If you are working with modelforms, full_clean (and from there clean) will be called automatically. If you are not doing so and want to ensure validation before saving, uncomment the next line.
        #self.full_clean()
        super(GetDates,self).save(*args,**kwargs)
于 2012-09-28T11:37:11.213 回答