Search code examples
pythondjangovalidationdjango-models

Django: Validate DateTimeField based on another DateTimeField


I'd like to validate a DateTimeField based on another DateTimeField in the same mode, like so:

class Operation(models.Model):
    machine = models.ForeignKey(Machine, on_delete=models.CASCADE)
    start = models.DateTimeField(auto_now_add=True)
    end = models.DateTimeField(
        null=True,
        blank=True,
        validators=[
            MinValueValidator(start)
        ]
    )

I get a TypeError exception when POSTing:

'<' not supported between instances of 'datetime.datetime' and 'DateTimeField'

These are the variables:

a datetime.datetime(2023, 1, 10, 0, 25, 29, tzinfo=zoneinfo.ZoneInfo(key='America/Sao_Paulo'))

b <django.db.models.fields.DateTimeField: start>

self <django.core.validators.MinValueValidator object at 0x104ded4d0>

I suppose I need to extract the datetime.datetime from the field, but I can't seem to do it from inside the model validator.

Any tips? Thank you.


Solution

  • Because Validators cannot compare between multiple fields. In your code, start in MinValueValidator(start) represents the entire field, not the actual value of an individual instance.

    You need Model.clean()

    class Operation(models.Model):
        machine = models.ForeignKey(Machine, on_delete=models.CASCADE)
        start = models.DateTimeField(auto_now_add=True)
        end = models.DateTimeField(null=True, blank=True)
    
        def clean(self):
            super().clean()
            if self.start and self.end:
                if self.start > self.end:
                    raise ValidationError("End datetime must be greater than start datetime.")
    

    I hope this will help.