mar*_*er_ 5 django validation model
我为模型验证器使用了一个名为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])
Run Code Online (Sandbox Code Playgroud)
“普通”验证器只会获取当前字段值。所以它不会做你想做的事情。但是,您可以添加一个干净的方法,并且 - 如果需要的话 - 像这样覆盖您的保存方法:
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)
Run Code Online (Sandbox Code Playgroud)