@@ -167,6 +167,9 @@ def build_json_resource_obj(fields, resource, resource_instance, resource_name):
167167def get_related_resource_type (relation ):
168168 if hasattr (relation , '_meta' ):
169169 relation_model = relation ._meta .model
170+ elif hasattr (relation , 'model' ):
171+ # the model type was explicitly passed as a kwarg to ResourceRelatedField
172+ relation_model = relation .model
170173 elif hasattr (relation , 'get_queryset' ) and relation .get_queryset () is not None :
171174 relation_model = relation .get_queryset ().model
172175 else :
@@ -270,8 +273,14 @@ def extract_relationships(fields, resource, resource_instance):
270273 try :
271274 source = field .source
272275 relation_instance_or_manager = getattr (resource_instance , source )
273- except AttributeError : # Skip fields defined on the serializer that don't correspond to a field on the model
274- continue
276+ except AttributeError :
277+ # if the field is not defined on the model then we check the serializer
278+ # and if no value is there we skip over the field completely
279+ serializer_method = getattr (field .parent , source , None )
280+ if serializer_method and hasattr (serializer_method , '__call__' ):
281+ relation_instance_or_manager = serializer_method (resource_instance )
282+ else :
283+ continue
275284
276285 relation_type = get_related_resource_type (field )
277286
@@ -432,8 +441,12 @@ def extract_included(fields, resource, resource_instance, included_resources):
432441 try :
433442 relation_instance_or_manager = getattr (resource_instance , field_name )
434443 except AttributeError :
435- # For ManyRelatedFields if `related_name` is not set we need to access `foo_set` from `source`
436- relation_instance_or_manager = getattr (resource_instance , field .child_relation .source )
444+ try :
445+ # For ManyRelatedFields if `related_name` is not set we need to access `foo_set` from `source`
446+ relation_instance_or_manager = getattr (resource_instance , field .child_relation .source )
447+ except AttributeError :
448+ serializer_method = getattr (current_serializer , field .source )
449+ relation_instance_or_manager = serializer_method (resource_instance )
437450
438451 new_included_resources = [key .replace ('%s.' % field_name , '' , 1 )
439452 for key in included_resources
0 commit comments