【问题标题】:Django CheckConstraints to check start_date greater than or equal todayDjango CheckConstraints 检查 start_date 是否大于或等于今天
【发布时间】:2022-01-06 08:00:19
【问题描述】:
    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=)

秒。

check = CheckConstraints(start_date__gte=timezone.now)

check = CheckConstraints(start_date__gte=TruncDay(Now))

当我尝试迁移时,此试用版出现错误 function cannot be resolved

如何查看 start_date 和今天?


提前感谢并为我的英语水平道歉。

【问题讨论】:

  • 我认为这回答了你的问题:stackoverflow.com/a/56860179/11993840
  • 答案是使用 Now()。但是当我尝试这种方式并迁移时,返回错误,“函数或表达式不能在检查子句中使用。”

标签: django django-models django-constraints


【解决方案1】:

我认为返回错误是因为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"
            )
    ]

文档中对此进行了解释,请参阅constraint reference 了解更多信息

【讨论】:

  • mariadb 不支持 CheckConstraint。 “函数或表达式 'CURRENT_TIME' 不能在检查子句中使用”错误发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 2012-01-03
  • 1970-01-01
  • 2011-07-08
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
相关资源
最近更新 更多