Skip to content

Commit c06a82d

Browse files
committed
Model serializer caching.
1 parent 62f78df commit c06a82d

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

rest_framework/serializers.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,10 @@ def raise_errors_on_nested_writes(method_name, serializer, validated_data):
682682
)
683683

684684

685+
MODEL_SERIALIZER_FIELDS_CACHE = {}
686+
MODEL_SERIALIZER_VALIDATORS_CACHE = {}
687+
688+
685689
class ModelSerializer(Serializer):
686690
"""
687691
A `ModelSerializer` is just a regular `Serializer`, except that:
@@ -802,6 +806,11 @@ def get_fields(self):
802806
Return the dict of field names -> field instances that should be
803807
used for `self.fields` when instantiating the serializer.
804808
"""
809+
cls = self.__class__
810+
811+
if cls in MODEL_SERIALIZER_FIELDS_CACHE:
812+
return copy.deepcopy(MODEL_SERIALIZER_FIELDS_CACHE[cls])
813+
805814
declared_fields = copy.deepcopy(self._declared_fields)
806815
model = getattr(self.Meta, 'model')
807816
depth = getattr(self.Meta, 'depth', 0)
@@ -837,6 +846,8 @@ def get_fields(self):
837846
# Add in any hidden fields.
838847
ret.update(hidden_fields)
839848

849+
MODEL_SERIALIZER_FIELDS_CACHE[cls] = ret
850+
840851
return ret
841852

842853
# Methods for determining the set of field names to include...
@@ -1217,12 +1228,21 @@ def get_validators(self):
12171228
if validators is not None:
12181229
return validators[:]
12191230

1231+
cls = self.__class__
1232+
1233+
if cls in MODEL_SERIALIZER_VALIDATORS_CACHE:
1234+
return MODEL_SERIALIZER_VALIDATORS_CACHE[cls][:]
1235+
12201236
# Otherwise use the default set of validators.
1221-
return (
1237+
validators = (
12221238
self.get_unique_together_validators() +
12231239
self.get_unique_for_date_validators()
12241240
)
12251241

1242+
MODEL_SERIALIZER_VALIDATORS_CACHE[cls] = validators
1243+
1244+
return validators
1245+
12261246
def get_unique_together_validators(self):
12271247
"""
12281248
Determine a default set of validators for any unique_together contraints.

0 commit comments

Comments
 (0)