Extends django check constraint to support annotations.
Project description
django-check-constraint
Complex check constraint support for Django.
Scenario:
Suppose you have a database function that returns the counts of null values in [i, ...n]
.
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;
Example:
SELECT public.non_null_count(1, null, null);
Outputs:
non_null_count
----------------
1
(1 row)
Defining a check constraint with this function
The equivalent of
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);
Usage
Converting this to django functions and annotated check contraints can be done using:
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)
Creating annotated check constraints
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_name_test_model_optional_field_provided',
),
]
:warning: Currently this doesn't support schema specific functions.
TODO's
[ ] Add support for schema based functions.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for django-check-constraint-1.0.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 423a8006159a1df93ead1106491ccbd7f9e9156e0148f238cca2f59aeaa439b2 |
|
MD5 | b465731c7e2d8ab4e984b30cd5de244b |
|
BLAKE2b-256 | 74799f3878d2a1ae1d01a8413253628ba16d7967f190cd9ddccd831d7e38e7fe |
Close
Hashes for django_check_constraint-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 131c2ecc9c4ba87df038ceef83851e485d91753a772765b068ac3d4fa2248dd7 |
|
MD5 | 6638e171b0e1bcbfcdeebfea9b95eaf9 |
|
BLAKE2b-256 | 3d6367daf34fc9fb4cda2d6f83913d342c4108e5327d3ec95166c56c6fc07687 |