Skip to content

Commit

Permalink
Add get_placeholder to handle automatic check constraint evaluation
Browse files Browse the repository at this point in the history
  • Loading branch information
sevdog authored and jimfunk committed Dec 13, 2023
1 parent cd354f7 commit 755aa86
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions netfields/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,9 @@ def get_db_prep_lookup(self, lookup_type, value, connection,
return super(_NetAddressField, self).get_db_prep_lookup(
lookup_type, value, connection=connection, prepared=prepared)

def get_placeholder(self, value, compiler, connection):
return "%s::{}".format(self.db_type(connection))

def formfield(self, **kwargs):
defaults = {'form_class': self.form_class()}
defaults.update(kwargs)
Expand Down
18 changes: 18 additions & 0 deletions test/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django import VERSION
from django.contrib.postgres.fields import ArrayField
from django.db.models import CASCADE, ForeignKey, Model

Expand Down Expand Up @@ -117,3 +118,20 @@ class AggregateTestChildModel(Model):
)
network = CidrAddressField()
inet = InetAddressField()


if VERSION >= (4, 1):
from django.db.models import F, Q, CheckConstraint


class ConstraintModel(Model):
network = CidrAddressField()
inet = InetAddressField()

class Meta:
constraints = (
CheckConstraint(
check=Q(network__net_contains=F('inet')),
name='inet_contained',
),
)
13 changes: 13 additions & 0 deletions test/tests/test_sql_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,3 +772,16 @@ def test_aggregate_network(self):
self.assertEqual(network_qs[0].agg_network, [None])
AggregateTestChildModel.objects.create(parent=parent, network=network, inet=inet)
self.assertEqual(network_qs[0].agg_network, [network])


class TestConstraints(TestCase):

@skipIf(VERSION < (4, 1), 'Check constraint validation is supported from django 4.1 onwards')
def test_check_constraint(self):
from test.models import ConstraintModel

inet = IPv4Interface('10.10.10.20/32')
network = IPv4Network('10.10.10.0/24')
model = ConstraintModel(inet=inet, network=network)
model.full_clean()
model.save()

0 comments on commit 755aa86

Please sign in to comment.