首页 > 解决方案 > 将表达式与 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 支持的任意表达式,并使用等式或不等式关系(例如=<=)将这些表达式与其他表达式或常量进行比较。

标签: djangodjango-modelsdjango-ormcheck-constraints

解决方案


推荐阅读