From a5f822d0671ce2412df666afa2b920039b302a0e Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 8 Jun 2016 15:55:09 +0100 Subject: [PATCH] Empty cases of .validated_data and .errors as lists not dicts for ListSerializer (#4180) --- rest_framework/serializers.py | 22 ++++++++++++++++++++++ tests/test_serializer_bulk_update.py | 2 ++ 2 files changed, 24 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 698730f53..3ec55724d 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -667,6 +667,28 @@ class ListSerializer(BaseSerializer): return self.instance + def is_valid(self, raise_exception=False): + # This implementation is the same as the default, + # except that we use lists, rather than dicts, as the empty case. + assert hasattr(self, 'initial_data'), ( + 'Cannot call `.is_valid()` as no `data=` keyword argument was ' + 'passed when instantiating the serializer instance.' + ) + + if not hasattr(self, '_validated_data'): + try: + self._validated_data = self.run_validation(self.initial_data) + except ValidationError as exc: + self._validated_data = [] + self._errors = exc.detail + else: + self._errors = [] + + if self._errors and raise_exception: + raise ValidationError(self.errors) + + return not bool(self._errors) + def __repr__(self): return unicode_to_repr(representation.list_repr(self, indent=1)) diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py index 8d7240a7b..567a32507 100644 --- a/tests/test_serializer_bulk_update.py +++ b/tests/test_serializer_bulk_update.py @@ -46,6 +46,7 @@ class BulkCreateSerializerTests(TestCase): serializer = self.BookSerializer(data=data, many=True) self.assertEqual(serializer.is_valid(), True) self.assertEqual(serializer.validated_data, data) + self.assertEqual(serializer.errors, []) def test_bulk_create_errors(self): """ @@ -76,6 +77,7 @@ class BulkCreateSerializerTests(TestCase): serializer = self.BookSerializer(data=data, many=True) self.assertEqual(serializer.is_valid(), False) self.assertEqual(serializer.errors, expected_errors) + self.assertEqual(serializer.validated_data, []) def test_invalid_list_datatype(self): """