@@ -272,6 +272,36 @@ def extract_relationships(cls, fields, resource, resource_instance):
272
272
273
273
return utils .format_keys (data )
274
274
275
+ @classmethod
276
+ def extract_relation_instance (cls , field_name , field , resource_instance , serializer ):
277
+ """
278
+ Determines what instance represents given relation and extracts it.
279
+
280
+ Relation instance is determined by given field_name or source configured on
281
+ field. As fallback is a serializer method called with name of field's source.
282
+ """
283
+ relation_instance = None
284
+
285
+ try :
286
+ relation_instance = getattr (resource_instance , field_name )
287
+ except AttributeError :
288
+ try :
289
+ # For ManyRelatedFields if `related_name` is not set
290
+ # we need to access `foo_set` from `source`
291
+ relation_instance = getattr (resource_instance , field .child_relation .source )
292
+ except AttributeError :
293
+ if hasattr (serializer , field .source ):
294
+ serializer_method = getattr (serializer , field .source )
295
+ relation_instance = serializer_method (resource_instance )
296
+ else :
297
+ # case when source is a simple remap on resource_instance
298
+ try :
299
+ relation_instance = getattr (resource_instance , field .source )
300
+ except AttributeError :
301
+ pass
302
+
303
+ return relation_instance
304
+
275
305
@classmethod
276
306
def extract_included (cls , fields , resource , resource_instance , included_resources ):
277
307
# this function may be called with an empty record (example: Browsable Interface)
@@ -304,19 +334,9 @@ def extract_included(cls, fields, resource, resource_instance, included_resource
304
334
if field_name not in [node .split ('.' )[0 ] for node in included_resources ]:
305
335
continue
306
336
307
- try :
308
- relation_instance = getattr (resource_instance , field_name )
309
- except AttributeError :
310
- try :
311
- # For ManyRelatedFields if `related_name` is not set we need to access `foo_set`
312
- # from `source`
313
- relation_instance = getattr (resource_instance , field .child_relation .source )
314
- except AttributeError :
315
- if not hasattr (current_serializer , field .source ):
316
- continue
317
- serializer_method = getattr (current_serializer , field .source )
318
- relation_instance = serializer_method (resource_instance )
319
-
337
+ relation_instance = cls .extract_relation_instance (
338
+ field_name , field , resource_instance , current_serializer
339
+ )
320
340
if isinstance (relation_instance , Manager ):
321
341
relation_instance = relation_instance .all ()
322
342
0 commit comments