mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-18 04:02:35 +03:00
fix: Make the instance variable of child serializer point to the correct list object instead of the entire list when validating ListSerializer
This commit is contained in:
parent
76110bf8a5
commit
c1ee7e75b1
|
@ -3,6 +3,7 @@ import pickle
|
|||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
from collections import ChainMap
|
||||
from collections.abc import Mapping
|
||||
|
||||
|
@ -11,6 +12,7 @@ from django.db import models
|
|||
|
||||
from rest_framework import exceptions, fields, relations, serializers
|
||||
from rest_framework.fields import Field
|
||||
|
||||
from .models import (
|
||||
ForeignKeyTarget, NestedForeignKeySource, NullableForeignKeySource
|
||||
)
|
||||
|
@ -843,3 +845,63 @@ class TestMultipleObjectsValidation(unittest.TestCase):
|
|||
many=True,
|
||||
partial=True,
|
||||
)
|
||||
|
||||
|
||||
class MyClass(models.Model):
|
||||
name = models.CharField(max_length=100)
|
||||
value = models.CharField(max_length=100, blank=True)
|
||||
|
||||
app_label = "test"
|
||||
|
||||
@property
|
||||
def is_valid(self):
|
||||
return self.name == 'valid'
|
||||
|
||||
|
||||
class MyClassSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = MyClass
|
||||
fields = ('id', 'name', 'value')
|
||||
|
||||
def validate_value(self, value):
|
||||
if value and not self.instance.is_valid:
|
||||
raise serializers.ValidationError(
|
||||
'Status cannot be set for invalid instance')
|
||||
return value
|
||||
|
||||
|
||||
class TestMultipleObjectsValidation(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.objs = [
|
||||
MyClass(name='valid'),
|
||||
MyClass(name='invalid'),
|
||||
MyClass(name='other'),
|
||||
]
|
||||
|
||||
def test_multiple_objects_are_validated_separately(self):
|
||||
|
||||
serializer = MyClassSerializer(
|
||||
data=[{'value': 'set', 'id': instance.id} for instance in
|
||||
self.objs],
|
||||
instance=self.objs,
|
||||
many=True,
|
||||
partial=True,
|
||||
)
|
||||
|
||||
assert not serializer.is_valid()
|
||||
assert serializer.errors == [
|
||||
{},
|
||||
{'value': ['Status cannot be set for invalid instance']},
|
||||
{'value': ['Status cannot be set for invalid instance']}
|
||||
]
|
||||
|
||||
def test_exception_raised_when_data_and_instance_length_different(self):
|
||||
|
||||
with self.assertRaises(AssertionError):
|
||||
serializer = MyClassSerializer(
|
||||
data=[{'value': 'set', 'id': instance.id} for instance in
|
||||
self.objs],
|
||||
instance=self.objs[:-1],
|
||||
many=True,
|
||||
partial=True,
|
||||
)
|
Loading…
Reference in New Issue
Block a user