Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add get_placeholder to handle automatic check constraint evaluation #125

Merged
merged 1 commit into from
Dec 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Loading