Search code examples
djangomodelvalidation

Can multiple values be used in a model validator in Django?


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

Solution

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