Merge pull request #2922 from thedrow/patch-11

Cache fields list for to_internal_value and to_representation
This commit is contained in:
Tom Christie 2015-06-23 08:53:32 +01:00
commit 1e678791de

View File

@ -14,6 +14,7 @@ from __future__ import unicode_literals
from django.db import models
from django.db.models.fields import FieldDoesNotExist, Field as DjangoModelField
from django.db.models import query
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from rest_framework.compat import (
postgres_fields,
@ -318,6 +319,20 @@ class Serializer(BaseSerializer):
self._fields[key] = value
return self._fields
@cached_property
def _writable_fields(self):
return [
field for field in self.fields.values()
if (not field.read_only) or (field.default is not empty)
]
@cached_property
def _readable_fields(self):
return [
field for field in self.fields.values()
if not field.write_only
]
def get_fields(self):
"""
Returns a dictionary of {field_name: field_instance}.
@ -392,10 +407,7 @@ class Serializer(BaseSerializer):
ret = OrderedDict()
errors = OrderedDict()
fields = [
field for field in self.fields.values()
if (not field.read_only) or (field.default is not empty)
]
fields = self._writable_fields
for field in fields:
validate_method = getattr(self, 'validate_' + field.field_name, None)
@ -423,7 +435,7 @@ class Serializer(BaseSerializer):
Object instance -> Dict of primitive datatypes.
"""
ret = OrderedDict()
fields = [field for field in self.fields.values() if not field.write_only]
fields = self._readable_fields
for field in fields:
try: