Skip to content

Set up serializer fields lazily on-demand. #1963

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

Merged
merged 1 commit into from
Oct 31, 2014
Merged
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
6 changes: 5 additions & 1 deletion rest_framework/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from django.forms import widgets
from django.utils import six
from django.utils.datastructures import SortedDict
from django.utils.functional import cached_property
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.settings import api_settings

Expand Down Expand Up @@ -197,7 +198,6 @@ def __init__(self, instance=None, data=None, files=None,
self.init_data = data
self.init_files = files
self.object = instance
self.fields = self.get_fields()

self._data = None
self._files = None
Expand All @@ -212,6 +212,10 @@ def __init__(self, instance=None, data=None, files=None,
#####
# Methods to determine which fields to use when (de)serializing objects.

@cached_property
def fields(self):
return self.get_fields()

def get_default_fields(self):
"""
Return the complete set of default fields for the object, as a dict.
Expand Down
5 changes: 3 additions & 2 deletions tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ class ClassWithQuerysetMethod(object):
self.assertEqual(value, ['BlogPost object'])

# Regression for #1129
def test_exception_for_incorect_fk(self):
def test_exception_for_incorrect_fk(self):
"""
Check that the exception message are correct if the source field
doesn't exist.
Expand All @@ -123,8 +123,9 @@ class Meta:
(serializers.ModelSerializer,),
attrs
)
serializer = TestSerializer(data={'name': 'foo'})
with self.assertRaises(AttributeError):
TestSerializer(data={'name': 'foo'})
serializer.fields


@unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6')
Expand Down
4 changes: 3 additions & 1 deletion tests/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,9 @@ def test_invalid_read_only_fields(self):
"""
Regression test for #652.
"""
self.assertRaises(AssertionError, PersonSerializerInvalidReadOnly, [])
serializer = PersonSerializerInvalidReadOnly()
with self.assertRaises(AssertionError):
serializer.fields

def test_serializer_data_is_cleared_on_save(self):
"""
Expand Down