1
    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.

jujube
  • 11
  • 3
  • I think this answers your question: https://stackoverflow.com/a/56860179/11993840 – barbaart Jan 06 '22 at 08:27
  • that answer is using Now(). But when I tried that way and migrate, the error returned , "functions or expressions cannot be used in check clause." – jujube Jan 07 '22 at 07:07

1 Answers1

2

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

barbaart
  • 837
  • 6
  • 14
  • CheckConstraint is not support in mariadb. "functions or expression 'CURRENT_TIME' cannot be userd in check clause" error occurs. – jujube Feb 17 '22 at 09:25