Prateek Narendra
Prateek Narendra

Reputation: 1937

Django - Save only time and validate start time is earlier than end time

I have a Django Model -

class Store(models.Model):
    store_id = models.AutoField(primary_key=True)
    contactNumber = PhoneField(blank=True, help_text='Contact number')
    startTime = models.TimeField(auto_now = False, auto_now,add = False)
    endTime = models.TimeField(auto_now = False, auto_now,add = False)

How do I ensure that startTime is always less than endTime ?

Upvotes: 1

Views: 1512

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477854

You can make use of a TimeField [Django-doc]. This will fetch objects and present these as datetime.time objects [Python-doc]. Furthermore it attaches some default widgets to it, that make it more convenient to work with forms where you enter time.

You thus can define this in your model with:

class Store(models.Model):
    store_id = models.AutoField(primary_key=True)
    contactNumber = PhoneField(blank=True, help_text='Contact number')
    start = models.TimeField()
    end = models.TimeField()

You can then override Model.clean() [Django-doc] to check if start is less than or equal to end. Furthermore since you can make use of the Django constraint framework [Django-doc], and try to enforce the constraints at the database side as well. Not all databases support this however:

from django.core.exceptions import ValidationError
from django.db.models import Q, F

class Store(models.Model):
    store_id = models.AutoField(primary_key=True)
    contactNumber = PhoneField(blank=True, help_text='Contact number')
    start = models.TimeField()
    end = models.TimeField()

    def clean(self):
        if self.start > self.end:
            raise ValidationError('Start should be before end')
        return super().clean()

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(start__lte=F('end')),
                name='start_before_end')
            )
        ]

Upvotes: 4

Related Questions