Skip to content

Commit

Permalink
Add test to reproduce problem with nullable fields part of a unique c…
Browse files Browse the repository at this point in the history
…onstraint

Ref encode#9378
  • Loading branch information
browniebroke committed Sep 11, 2024
1 parent b25028a commit 335a27f
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions tests/test_model_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1400,3 +1400,32 @@ class Meta:
serializer.save()

self.assertEqual(instance.char_field, 'value changed by signal')


class Tag(models.Model):
name = models.CharField(max_length=100)


class UniqueConstraintModel(models.Model):
title = models.CharField(max_length=100)
age = models.IntegerField(null=True)
tag = models.ForeignKey(Tag, on_delete=models.CASCADE, related_name='instances', null=True)

class Meta:
constraints = [
# Unique constraint on 2 nullable fields
models.UniqueConstraint(name='unique_constraint', fields=('age', 'tag'))
]


class TestUniqueConstraintWithNullableFields(TestCase):
def test_nullable_unique_constraint_fields_are_not_required(self):
class UniqueConstraintSerializer(serializers.ModelSerializer):
class Meta:
model = UniqueConstraintModel
fields = '__all__'

serializer = UniqueConstraintSerializer(data={'title': 'Bob'})
self.assertTrue(serializer.is_valid(), serializer.errors)
result = serializer.save()
self.assertIsInstance(result, UniqueConstraintModel)

0 comments on commit 335a27f

Please sign in to comment.