我有一个模型使用一个名为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])
答案 0 :(得分:4)
“普通”验证器只会获取当前字段值。所以它不会做你想做的事情。但是,您可以添加一个干净的方法,并且 - 如果需要 - 应该覆盖您的保存方法:
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)