Set hourly limit on DateTimeField Django

Question:

Models.py:

class Event(models.Model):
    start = models.DateTimeField(default=timezone.now)
    end = models.DateTimeField()

How can I set hard limit for setting end_date?

So if the user wants to set anything over 5hours from start system won’t let him do that.

Asked By: rafaelHTML

||

Answers:

You can do it in the database level using constraints

from datetime import timedelta
from django.db import models
from django.db.models import CheckConstraint, Q, F

class Event(models.Model):
    start = models.DateTimeField(default=timezone.now)
    end = models.DatetimeField()

    class Meta:
        constraints = [
            CheckConstraint(
                check=Q(end__lte=F('start') + timedelta(hours=5)), 
                name='check_end_datetime',
            ),
        ]

The run manage.py makemigrations and manage.py migrate to alter the database.

Answered By: Shohan Dutta Roy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.