扩展django check constraint以支持注解。
项目描述
django-check-constraint
扩展 Django的Check 约束,支持UDF(用户定义函数/数据库函数)和注解。
安装
$ pip install django-check-constraint
将 check_constraint
添加到 INSTALLED APPS 列表中。
INSTALLED_APPS = [
...
"check_constraint",
...
]
场景
假设你有一个数据库函数,该函数返回 [i, ...n]
中null值的计数。
CREATE OR REPLACE FUNCTION public.non_null_count(VARIADIC arg_array ANYARRAY)
RETURNS BIGINT AS
$$
SELECT COUNT(x) FROM UNNEST($1) AS x
$$ LANGUAGE SQL IMMUTABLE;
示例
SELECT public.non_null_count(1, null, null);
输出
non_null_count
----------------
1
(1 row)
使用此函数定义检查约束
(PostgresSQL) 的等效形式
ALTER TABLE app_name_test_modoel ADD CONSTRAINT app_name_test_model_optional_field_provided
CHECK(non_null_count(amount::integer , amount_off::integer, percentage::integer) = 1);
用法
可以使用以下方式将此转换为django函数和注解检查约束:
function.py
from django.db.models import Func, SmallIntegerField, TextField
from django.db.models.functions import Cast
class NotNullCount(Func):
function = 'non_null_count'
def __init__(self, *expressions, **extra):
filter_exp = [
Cast(exp, TextField()) for exp in expressions if isinstance(exp, str)
]
if 'output_field' not in extra:
extra['output_field'] = SmallIntegerField()
if len(expressions) < 2:
raise ValueError('NotNullCount must take at least two expressions')
super().__init__(*filter_exp, **extra)
创建注解检查约束
from django.db import models
from django.db.models import Q
from check_constraint.models import AnnotatedCheckConstraint
class TestModel(models.Model):
amount = models.DecimalField(max_digits=9, decimal_places=2, null=True, blank=True)
amount_off = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
percentage = models.DecimalField(max_digits=3, decimal_places=0, null=True, blank=True)
class Meta:
constraints = [
AnnotatedCheckConstraint(
check=Q(not_null_count=1),
annotations={
'not_null_count': (
NotNullCount(
'amount',
'amount_off',
'percentage',
)
),
},
name='%(app_label)s_%(class)s_optional_field_provided',
),
]
待办事项
- 添加对基于模式的函数的支持。
- 添加关于MySQL缺少用户定义检查约束支持的警告。
- 删除跳过的sqlite3测试。
项目详情
下载文件
下载您平台对应的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。
源分布
django-check-constraint-1.0.18.tar.gz (13.6 kB 查看散列值)
构建分布
关闭
django-check-constraint-1.0.18.tar.gz的散列值
算法 | 散列摘要 | |
---|---|---|
SHA256 | e1fc7074def6a21576a3170f59e0c656163f81c0fb2962723980016877e35f07 |
|
MD5 | 466c000560b90ffeb52b508f1ace4e79 |
|
BLAKE2b-256 | d330d113b6f1a2f0a0422f5853ec49885bdd1bd59a9634b751d834a505609cf5 |
关闭
django_check_constraint-1.0.18-py3-none-any.whl的散列值
算法 | 散列摘要 | |
---|---|---|
SHA256 | 2dd1942d1314415ab93b7a2242a34139b576069b58d9aaeb70b810cc13f6578f |
|
MD5 | e23b635194d38c0705b25f9d5f0829d6 |
|
BLAKE2b-256 | 1c741d10331fbce9104a9d669c816a304863e3cc114a4d3824279a712459a61d |