Django模型验证器中可以使用多个值吗? [英] Can multiple values be used in django a model validator?

查看:90
本文介绍了Django模型验证器中可以使用多个值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got a model using a validation class called CompareDates for my model validators and I want to pass the validator two field values. However I'm unsure of how to use multiple field values in a validator.

我希望能够在日期之间进行比较,以验证整个模型,但似乎您无法为传递给验证器的值建立关键字,或者我遗漏了什么?

I want to be able to make comparisons between the dates in order to validate the model as a whole but it doesn't seem like you can keyword the values passed to the validators, or am I missing something?

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])

推荐答案

常规"验证器将仅获取当前字段值.因此,它不会执行您要尝试执行的操作.但是,您可以添加一个干净的方法,并且-如果需要的话-覆盖您的save方法,如下所示:

The "normal" validators will only get the current fields value. So it will not do what you are trying to do. However, you can add a clean method, and - if need should be - overwrite your save method like that:

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)

这篇关于Django模型验证器中可以使用多个值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆