0
    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()))
        ]

像上面的代码一样,我想添加 CheckConstraint 来检查 start_date 是否大于或等于今天。
但是,在 makemigration 和 migrate 之后,发生了错误。

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

我尝试了两种方法。

第一的。

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

但是,迁移文件具有 timezone.now() 方法的结果,例如 datetime(2022, 01, 06, tzinfo=<UTC>)

第二。

check = CheckConstraints(start_date__gte=timezone.now)

check = CheckConstraints(start_date__gte=TruncDay(Now))

function cannot be resolved当我尝试迁移时,此试验会出错。

如何查看 start_date 和今天?


提前感谢并为我的英语技能道歉。

4

1 回答 1

0

我认为该错误返回是因为CheckConstraint.
你的进口:from django.db import models所以你应该使用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"
            )
    ]

它在文档中进行了解释,有关更多信息,请参阅约束参考

于 2022-01-07T08:41:21.117 回答