django - 将表达式与 CHECK 约束中的常量进行比较
问题描述
我想使用 Django使用 PostgreSQLs 函数向表CheckConstraint
添加check
约束num_nonnulls()
,类似于:
create table foo(
a text,
b int,
[...],
check num_nonnulls(a, b, ...) = n);
n
是一个常数,但对于不同的表可能会有所不同(大多数情况下会是这样1
,但我想找到一个通用的解决方案)。这是我走了多远:
class Foo(models.Model):
a = models.TextField(null=True)
b = models.IntegerField(null=True)
[...]
class Meta:
constraints = [
models.CheckConstraint(
check=models.ExpressionWrapper(
models.Func('a', 'b', function='num_nonnulls'),
models.BooleanField()),
name='num_nonnulls_check')]
这当然缺少将结果num_nonnulls()
与某个常量整数进行比较的步骤。我尝试定义一个函数来做到这一点:
def equals(a, b):
return models.Func(a, b, template='%(expressions[0])s = %(expressions[1])s')
但这不起作用,因为模板参数expressions
(我认为)是一个字符串(我认为%
-template 字符串没有这种语法来提取参数的一部分)。
我从这里去哪里?
我想找到一个解决方案,允许我使用 Django ORM 支持的任意表达式,并使用等式或不等式关系(例如=
或<=
)将这些表达式与其他表达式或常量进行比较。
解决方案
推荐阅读
- charts - 表格在可视化 GeoChart 中包含比预期更多的列(预期 3 列)
- php - 如何仅在 wordpress 主页上加载 Bootstrap
- swift - 'CaseIterable' 协议的 allCases 和 AllCases 有什么区别?
- oauth-2.0 - 视图函数未返回有效响应。返回类型必须是字符串,dict
- powerbi - 如何合并2个堆积柱形图?
- python - 无法在 python 3.9 中使用 pip 安装 pylint
- javascript - Javascript 检查数组是否为空或未定义
- python - 浮点数显示为浮点数,但整数在python中显示为整数
- algorithm - 三栈实现k栈
- javascript - 溢出自动(可滚动)内容的锚点