Django CheckConstraints to check start_date greater than or equal today

1.3k Views Asked by At
    from django.db import models
    from django.db.models.functions import Now, TruncDay
    
    class Foo(models.Model):
      start_date = models.DateTimeField()
      end_date = models.DateTimeField()
    
      class Meta:
        constraints = [
          name="start_date must be greater than or equal today",
          check=CheckConstraints(start_date__gte=TruncDay(Now()))
        ]

like above code, I want to add CheckConstraint to check whether start_date is greater than or equal with today.
but, after makemigration and migrate, error happened.

functions or expression 'CURRENT_TIME' cannot be userd in check clause

I tried two ways.

first.

check = CheckConstraints(start_date__gte=timezone.now())

but, Migration File has result of timezone.now() method, like datetime(2022, 01, 06, tzinfo=<UTC>)

second.

check = CheckConstraints(start_date__gte=timezone.now)

and

check = CheckConstraints(start_date__gte=TruncDay(Now))

this trial make error function cannot be resolved when I tried to migrate.

How can I check start_date and today?


thanks and apologize for my English skills in advance.

1

There are 1 best solutions below

1
On

I think that error returned because of CheckConstraint.
Your import: from django.db import models so you should use models.CheckConstraint()

from django.db import models
from django.db.models.functions import Now
from django.db.models import Q    

class Foo(models.Model):
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

    class Meta:
        constraints = [
            models.CheckConstraint(
                check=Q(start_date__gte=Now()),
                name = "start_date must be greater than or equal today"
            )
    ]

It is explained in the docs, see constraint reference for more info