Skip to content

Commit e2a4559

Browse files
saadullahaleemderonnaxMehrazRummantheomegajornvanwier
authored
Fix validation for ListSerializer (#8979)
* fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer * fix formatting issues for list serializer validation fix * fix imports sorting for list serializer tests * remove django 2.2 from docs index (#8982) * Declared Django 4.2 support in README.md (#8985) * Fix Links in Documentation to Django `reverse` and `reverse_lazy` (#8986) * Fix Django Docs url in reverse.md Django URLs of the documentation of `reverse` and `reverse_lazy` were wrong. * Update reverse.md * fix URLPathVersioning reverse fallback (#7247) * fix URLPathVersioning reverse fallback * add test for URLPathVersioning reverse fallback * Update tests/test_versioning.py --------- Co-authored-by: Jorn van Wier <[email protected]> Co-authored-by: Asif Saif Uddin <[email protected]> * Make set_value a method within `Serializer` (#8001) * Make set_value a static method for Serializers As an alternative to #7671, let the method be overridden if needed. As the function is only used for serializers, it has a better place in the Serializer class. * Set `set_value` as an object (non-static) method * Add tests for set_value() These tests follow the examples given in the method. * fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer * Make set_value a method within `Serializer` (#8001) * Make set_value a static method for Serializers As an alternative to #7671, let the method be overridden if needed. As the function is only used for serializers, it has a better place in the Serializer class. * Set `set_value` as an object (non-static) method * Add tests for set_value() These tests follow the examples given in the method. * fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer * fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer * fix formatting issues for list serializer validation fix * fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer * fix formatting issues for list serializer validation fix * fix linting * Update rest_framework/serializers.py Co-authored-by: Sergei Shishov <[email protected]> * Update rest_framework/serializers.py Co-authored-by: Sergei Shishov <[email protected]> * fix: instance variable in list serializer, remove commented code --------- Co-authored-by: Mathieu Dupuy <[email protected]> Co-authored-by: Mehraz Hossain Rumman <[email protected]> Co-authored-by: Dominik Bruhn <[email protected]> Co-authored-by: jornvanwier <[email protected]> Co-authored-by: Jorn van Wier <[email protected]> Co-authored-by: Asif Saif Uddin <[email protected]> Co-authored-by: Étienne Beaulé <[email protected]> Co-authored-by: Sergei Shishov <[email protected]>
1 parent d252d22 commit e2a4559

File tree

2 files changed

+74
-1
lines changed

2 files changed

+74
-1
lines changed

rest_framework/serializers.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,6 +609,12 @@ def __init__(self, *args, **kwargs):
609609
self.min_length = kwargs.pop('min_length', None)
610610
assert self.child is not None, '`child` is a required argument.'
611611
assert not inspect.isclass(self.child), '`child` has not been instantiated.'
612+
613+
instance = kwargs.get('instance', [])
614+
data = kwargs.get('data', [])
615+
if instance and data:
616+
assert len(data) == len(instance), 'Data and instance should have same length'
617+
612618
super().__init__(*args, **kwargs)
613619
self.child.bind(field_name='', parent=self)
614620

@@ -683,7 +689,13 @@ def to_internal_value(self, data):
683689
ret = []
684690
errors = []
685691

686-
for item in data:
692+
for idx, item in enumerate(data):
693+
if (
694+
hasattr(self, 'instance')
695+
and self.instance
696+
and len(self.instance) > idx
697+
):
698+
self.child.instance = self.instance[idx]
687699
try:
688700
validated = self.child.run_validation(item)
689701
except ValidationError as exc:

tests/test_serializer.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import pickle
33
import re
44
import sys
5+
import unittest
56
from collections import ChainMap
67
from collections.abc import Mapping
78

@@ -783,3 +784,63 @@ def test_nested_key(self):
783784
ret = {'a': 1}
784785
self.s.set_value(ret, ['x', 'y'], 2)
785786
assert ret == {'a': 1, 'x': {'y': 2}}
787+
788+
789+
class MyClass(models.Model):
790+
name = models.CharField(max_length=100)
791+
value = models.CharField(max_length=100, blank=True)
792+
793+
app_label = "test"
794+
795+
@property
796+
def is_valid(self):
797+
return self.name == 'valid'
798+
799+
800+
class MyClassSerializer(serializers.ModelSerializer):
801+
class Meta:
802+
model = MyClass
803+
fields = ('id', 'name', 'value')
804+
805+
def validate_value(self, value):
806+
if value and not self.instance.is_valid:
807+
raise serializers.ValidationError(
808+
'Status cannot be set for invalid instance')
809+
return value
810+
811+
812+
class TestMultipleObjectsValidation(unittest.TestCase):
813+
def setUp(self):
814+
self.objs = [
815+
MyClass(name='valid'),
816+
MyClass(name='invalid'),
817+
MyClass(name='other'),
818+
]
819+
820+
def test_multiple_objects_are_validated_separately(self):
821+
822+
serializer = MyClassSerializer(
823+
data=[{'value': 'set', 'id': instance.id} for instance in
824+
self.objs],
825+
instance=self.objs,
826+
many=True,
827+
partial=True,
828+
)
829+
830+
assert not serializer.is_valid()
831+
assert serializer.errors == [
832+
{},
833+
{'value': ['Status cannot be set for invalid instance']},
834+
{'value': ['Status cannot be set for invalid instance']}
835+
]
836+
837+
def test_exception_raised_when_data_and_instance_length_different(self):
838+
839+
with self.assertRaises(AssertionError):
840+
MyClassSerializer(
841+
data=[{'value': 'set', 'id': instance.id} for instance in
842+
self.objs],
843+
instance=self.objs[:-1],
844+
many=True,
845+
partial=True,
846+
)

0 commit comments

Comments
 (0)