我有使用验证类叫做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])
“正常”验证将只能得到当前的字段值。 所以它不会做你正在尝试做的。 但是,您可以添加一个干净的方法,和 - 如果需要应该是 - 覆盖你的保存方式类似:
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)