Ensure context is passed to dynamically added fields. Fixes #476.

This commit is contained in:
Tom Christie 2012-12-14 19:59:21 +00:00
parent 9eaf8e4330
commit 39b01d6802
2 changed files with 6 additions and 7 deletions

View File

@ -171,10 +171,6 @@ class BaseSerializer(Field):
for key in self.opts.exclude:
ret.pop(key, None)
# Initialize the fields
for key, field in ret.items():
field.initialize(parent=self, field_name=key)
return ret
#####
@ -214,6 +210,7 @@ class BaseSerializer(Field):
ret.fields = {}
for field_name, field in self.fields.items():
field.initialize(parent=self, field_name=field_name)
key = self.get_field_key(field_name)
value = field.field_to_native(obj, field_name)
ret[key] = value
@ -227,6 +224,7 @@ class BaseSerializer(Field):
"""
reverted_data = {}
for field_name, field in self.fields.items():
field.initialize(parent=self, field_name=field_name)
try:
field.field_from_native(data, files, field_name, reverted_data)
except ValidationError as err:
@ -407,7 +405,6 @@ class ModelSerializer(Serializer):
field = self.get_field(model_field)
if field:
field.initialize(parent=self, field_name=model_field.name)
ret[model_field.name] = field
for field_name in self.opts.read_only_fields:

View File

@ -149,7 +149,6 @@ class IntegrationTestPaginationAndFiltering(TestCase):
class PassOnContextPaginationSerializer(pagination.PaginationSerializer):
class Meta:
object_serializer_class = serializers.Serializer
@ -179,9 +178,12 @@ class UnitTestPagination(TestCase):
self.assertEquals(serializer.data['results'], self.objects[20:])
def test_context_available_in_result(self):
"""
Ensure context gets passed through to the object serializer.
"""
serializer = PassOnContextPaginationSerializer(self.first_page)
serializer.data
results = serializer.fields[serializer.results_field]
# assertIs is available in Python 2.7
self.assertTrue(serializer.context is results.context)