@@ -182,38 +182,39 @@ def to_representation(self, instance):
182
182
183
183
for field in readable_fields :
184
184
try :
185
- request = self .context .get ('request' , None )
186
- is_included = field .source in get_included_resources (request , self )
187
- if not is_included \
188
- and isinstance (field , ModelSerializer ) \
189
- and hasattr (instance , field .source + "_id" ):
190
- attribute = getattr (instance , field .source + "_id" )
191
- if attribute is None :
192
- ret [field .field_name ] = None
193
- continue
194
- resource_type = get_resource_type_from_serializer (field )
195
- if resource_type :
196
- ret [field .field_name ] = OrderedDict ([("type" , resource_type ),
197
- ("id" , attribute )])
198
- continue
199
-
200
- attribute = field .get_attribute (instance )
185
+ field_representation = self ._get_field_representation (field , instance )
186
+ ret [field .field_name ] = field_representation
201
187
except SkipField :
202
188
continue
203
189
204
- # We skip `to_representation` for `None` values so that fields do
205
- # not have to explicitly deal with that case.
206
- #
207
- # For related fields with `use_pk_only_optimization` we need to
208
- # resolve the pk value.
209
- check_for_none = attribute .pk if isinstance (attribute , PKOnlyObject ) else attribute
210
- if check_for_none is None :
211
- ret [field .field_name ] = None
212
- else :
213
- ret [field .field_name ] = field .to_representation (attribute )
214
-
215
190
return ret
216
191
192
+ def _get_field_representation (self , field , instance ):
193
+ request = self .context .get ('request' , None )
194
+ is_included = field .source in get_included_resources (request )
195
+ if not is_included and isinstance (field , ModelSerializer ) and hasattr (instance , f'{ field .source } _id' ):
196
+ attribute = getattr (instance , f'{ field .source } _id' )
197
+
198
+ if attribute is None :
199
+ return None
200
+
201
+ resource_type = get_resource_type_from_serializer (field )
202
+ if resource_type :
203
+ return OrderedDict ([('type' , resource_type ), ('id' , attribute )])
204
+
205
+ attribute = field .get_attribute (instance )
206
+
207
+ # We skip `to_representation` for `None` values so that fields do
208
+ # not have to explicitly deal with that case.
209
+ #
210
+ # For related fields with `use_pk_only_optimization` we need to
211
+ # resolve the pk value.
212
+ check_for_none = attribute .pk if isinstance (attribute , PKOnlyObject ) else attribute
213
+ if check_for_none is None :
214
+ return None
215
+ else :
216
+ return field .to_representation (attribute )
217
+
217
218
218
219
class PolymorphicSerializerMetaclass (SerializerMetaclass ):
219
220
"""
0 commit comments