Django中的模型验证器可以使用多个值吗?

z4iuyo4d  于 2023-03-13  发布在  Go
关注(0)|答案(1)|浏览(106)

我有一个模型,它使用一个名为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])
brgchamk

brgchamk1#

“普通”验证器只会得到当前字段的值,所以它不会做你想做的事情。但是,你可以添加一个干净的方法,并且-如果需要的话-覆盖你的保存方法,如下所示:

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)

相关问题