I need to write a script where it validates the end date is greater than the start date.
Also the start date/end date can not be before the current date. This needs to be written in Django 1.8.
You can override the Model.clean(..)
method [Django-doc] for this. If you use a ModelForm
[Django-doc], then it will automatically call .clean()
on the model instance to check if the constraint is satisfied.
from django.db import models
from django.utils import timezone
class MyModel(models.Model):
start = models.DateTimeField()
end = models.DateTimeField()
def clean(self):
super().clean()
if not (timezone.now() <= self.start <= self.end):
raise ValidationError('Invalid start and end datetime')
As of django-2.2, you can use constraints
[Django-doc] in the Meta
:
# since Django-2.2
from django.db import models
from django.db.models import F, Q
from django.db.models.functions import Now
class MyModel(models.Model):
start = models.DateTimeField()
end = models.DateTimeField()
def clean(self):
# ...
pass
class Meta:
constraints = [
models.CheckConstraint(
check=Q(start__lte=F('end'), start__gte=Now()),
name='correct_datetime'
),
]
Given the database system supports this, the constraints will be enforced at the database level as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With