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

Set child instance to an instance instead of QuerySet. #2720

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 2 additions & 0 deletions rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -545,6 +545,8 @@ def to_internal_value(self, data):

for item in data:
try:
if isinstance(self.instance, QuerySet):
self.child.instance = self.instance.get(pk=item['id'])
validated = self.child.run_validation(item)
except ValidationError as exc:
errors.append(exc.detail)
Expand Down
36 changes: 36 additions & 0 deletions tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,42 @@ class Meta:
fields = ('renamed',)


class UniqueTogetherModel(models.Model):
foo = models.IntegerField()
bar = models.IntegerField()

class Meta(object):
unique_together = ('foo', 'bar')


class ExampleSerializer(serializers.ModelSerializer):
class Meta(object):
model = UniqueTogetherModel


class TestUniqueTogether(TestCase):
def test_validation(self):
"""
Ensure that validation works when model has unique together validation.
"""
UniqueTogetherModel.objects.all().delete()
obj = UniqueTogetherModel.objects.create(foo=1, bar=2)

s = ExampleSerializer(
UniqueTogetherModel.objects.all(),
data=[
{
'foo': 5,
'id': obj.pk,
}
],
partial=True,
many=True,
)

s.is_valid(raise_exception=True)


class TestPreSaveValidationExclusionsSerializer(TestCase):
def test_renamed_fields_are_model_validated(self):
"""
Expand Down