[4.1.x] Fixed #33905 -- Fixed CheckConstraint() validation on range fields.

Bug in 667105877e.

Backport of e0ae1363ec from main
This commit is contained in:
David Sanders 2022-08-09 16:16:23 +10:00 committed by Mariusz Felisiak
parent 6b0193146d
commit e215948f0d
3 changed files with 41 additions and 0 deletions

View File

@ -78,6 +78,9 @@ class RangeField(models.Field):
def _choices_is_value(cls, value):
return isinstance(value, (list, tuple)) or super()._choices_is_value(value)
def get_placeholder(self, value, compiler, connection):
return "%s::{}".format(self.db_type(connection))
def get_prep_value(self, value):
if value is None:
return None

View File

@ -32,3 +32,6 @@ Bugfixes
* Fixed a bug in Django 4.1 that caused a crash of model validation on
``UniqueConstraint()`` with field names in ``expressions`` (:ticket:`33902`).
* Fixed a bug in Django 4.1 that caused an incorrect validation of
``CheckConstraint()`` with range fields on PostgreSQL (:ticket:`33905`).

View File

@ -113,6 +113,41 @@ class SchemaTests(PostgreSQLTestCase):
timestamps_inner=(datetime_1, datetime_2),
)
def test_check_constraint_range_contains(self):
constraint = CheckConstraint(
check=Q(ints__contains=(1, 5)),
name="ints_contains",
)
msg = f"Constraint “{constraint.name}” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(RangesModel, RangesModel(ints=(6, 10)))
def test_check_constraint_range_lower_upper(self):
constraint = CheckConstraint(
check=Q(ints__startswith__gte=0) & Q(ints__endswith__lte=99),
name="ints_range_lower_upper",
)
msg = f"Constraint “{constraint.name}” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(RangesModel, RangesModel(ints=(-1, 20)))
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(RangesModel, RangesModel(ints=(0, 100)))
constraint.validate(RangesModel, RangesModel(ints=(0, 99)))
def test_check_constraint_range_lower_with_nulls(self):
constraint = CheckConstraint(
check=Q(ints__isnull=True) | Q(ints__startswith__gte=0),
name="ints_optional_positive_range",
)
constraint.validate(RangesModel, RangesModel())
constraint = CheckConstraint(
check=Q(ints__startswith__gte=0),
name="ints_positive_range",
)
msg = f"Constraint “{constraint.name}” is violated."
with self.assertRaisesMessage(ValidationError, msg):
constraint.validate(RangesModel, RangesModel())
def test_opclass(self):
constraint = UniqueConstraint(
name="test_opclass",