Skip to content

Commit 755aa86

Browse files
sevdogjimfunk
authored andcommitted
Add get_placeholder to handle automatic check constraint evaluation
1 parent cd354f7 commit 755aa86

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

netfields/fields.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,9 @@ def get_db_prep_lookup(self, lookup_type, value, connection,
120120
return super(_NetAddressField, self).get_db_prep_lookup(
121121
lookup_type, value, connection=connection, prepared=prepared)
122122

123+
def get_placeholder(self, value, compiler, connection):
124+
return "%s::{}".format(self.db_type(connection))
125+
123126
def formfield(self, **kwargs):
124127
defaults = {'form_class': self.form_class()}
125128
defaults.update(kwargs)

test/models.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from django import VERSION
12
from django.contrib.postgres.fields import ArrayField
23
from django.db.models import CASCADE, ForeignKey, Model
34

@@ -117,3 +118,20 @@ class AggregateTestChildModel(Model):
117118
)
118119
network = CidrAddressField()
119120
inet = InetAddressField()
121+
122+
123+
if VERSION >= (4, 1):
124+
from django.db.models import F, Q, CheckConstraint
125+
126+
127+
class ConstraintModel(Model):
128+
network = CidrAddressField()
129+
inet = InetAddressField()
130+
131+
class Meta:
132+
constraints = (
133+
CheckConstraint(
134+
check=Q(network__net_contains=F('inet')),
135+
name='inet_contained',
136+
),
137+
)

test/tests/test_sql_fields.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -772,3 +772,16 @@ def test_aggregate_network(self):
772772
self.assertEqual(network_qs[0].agg_network, [None])
773773
AggregateTestChildModel.objects.create(parent=parent, network=network, inet=inet)
774774
self.assertEqual(network_qs[0].agg_network, [network])
775+
776+
777+
class TestConstraints(TestCase):
778+
779+
@skipIf(VERSION < (4, 1), 'Check constraint validation is supported from django 4.1 onwards')
780+
def test_check_constraint(self):
781+
from test.models import ConstraintModel
782+
783+
inet = IPv4Interface('10.10.10.20/32')
784+
network = IPv4Network('10.10.10.0/24')
785+
model = ConstraintModel(inet=inet, network=network)
786+
model.full_clean()
787+
model.save()

0 commit comments

Comments
 (0)