如何重写此postgres约束使其更符合django 2.2?

问题描述 投票:3回答:1

这是我为postgres为检查约束编写的原始查询

   ALTER TABLE rea_asplinkage ADD CONSTRAINT asp_sub_project_positive_integer
        CHECK (
            jsonb_typeof(linkage-> 'root' -> 'in_sub_project') is not distinct from 'number'
        and (linkage->'root'->>'in_sub_project')::numeric % 1 = 0
        and (linkage->'root'->>'in_sub_project')::numeric > 0
        );

而且我创建迁移的方式是这种方式

# Generated by Django 2.2.10 on 2020-05-16 12:59

from django.db import connection, migrations



class Migration(migrations.Migration):

    dependencies = [("rea", "0029_asplinkage")]

    operations = [
        migrations.RunSQL(
            sql="""
            ALTER TABLE rea_asplinkage ADD CONSTRAINT asp_sub_project_positive_integer
            CHECK (
                jsonb_typeof(linkage-> 'root' -> 'in_sub_project') is not distinct from 'number'
            and (linkage->'root'->>'in_sub_project')::numeric % 1 = 0
            and (linkage->'root'->>'in_sub_project')::numeric > 0
            );
            """,
            reverse_sql="""
                ALTER TABLE rea_asplinkage DROP CONSTRAINT "asp_sub_project_positive_integer";
            """,
        )
    ]

这可行。

但是这意味着我的原始模型未在ASPLinkage模型的class Meta中显示约束。>

class ASPLinkage(TimeStampedModel, SoftDeletableModel, PersonStampedModel, OrganizationOwnedModel):
    linkage = JSONField(default=default_linkage_for_asp)

    objects = OrganizationOwnedSoftDeletableManager()

我已经尝试在类Meta内创建约束时使用ExpressionWrapperRawSQL,但仍然无法正常工作。

供参考,我看了https://github.com/django/django/blob/master/tests/constraints/models.py#L12中的示例

我也研究了通过https://realpython.com/create-django-index-without-downtime/#when-django-generates-a-new-migration的独立数据库和状态迁移

但是我仍然无法使它正常工作

这有可能吗?

更新

为了更好的可读性,让我写一个问题的摘要。

  1. 我想在JSONField上写约束。
  2. 我可以直接在Postgres上做到这一点
  3. 因此,我可以在迁移文件中使用原始sql来完成
  4. 但是我不能使用Django模型meta / CheckConstraint做等效的操作,这通常是任何人做的。参见https://docs.djangoproject.com/en/3.0/ref/models/constraints/
  5. 所以我如何重写此原始sql以在postgres中以Django的方式对jsonfield产生约束?

这是我为检查约束的postgres写的原始查询ALTER TABLE rea_asplinkage ADD CONSTRAINT asp_sub_project_positive_integer CHECK(jsonb_typeof(linkage -...

django postgresql database-migration check-constraints
1个回答
1
投票

为了从you'll need to register two new JSONField transforms/lookups开始在Django 2.2 JSONField上实现这一目标。

您首先要为support for conditional expressions was only added in the upcoming 3.1 release键访问注册查找

© www.soinside.com 2019 - 2024. All rights reserved.