1+ import collections
12import json
23
3- from rest_framework .fields import MISSING_ERROR_MESSAGE
4+ from rest_framework .fields import MISSING_ERROR_MESSAGE , SerializerMethodField
45from rest_framework .relations import *
56from django .utils .translation import ugettext_lazy as _
67from django .db .models .query import QuerySet
1011 get_resource_type_from_queryset , get_resource_type_from_instance , \
1112 get_included_serializers , get_resource_type_from_serializer
1213
14+ LINKS_PARAMS = ['self_link_view_name' , 'related_link_view_name' , 'related_link_lookup_field' , 'related_link_url_kwarg' ]
15+
1316
1417class ResourceRelatedField (PrimaryKeyRelatedField ):
1518 self_link_view_name = None
@@ -171,7 +174,6 @@ def get_choices(self, cutoff=None):
171174 ])
172175
173176
174-
175177class SerializerMethodResourceRelatedField (ResourceRelatedField ):
176178 """
177179 Allows us to use serializer method RelatedFields
@@ -190,13 +192,16 @@ def __init__(self, child_relation=None, *args, **kwargs):
190192 # DRF 3.1 doesn't expect the `many` kwarg
191193 kwargs .pop ('many' , None )
192194 model = kwargs .pop ('model' , None )
195+ if child_relation is not None :
196+ self .child_relation = child_relation
193197 if model :
194198 self .model = model
195- super (SerializerMethodResourceRelatedField , self ).__init__ (child_relation , * args , ** kwargs )
199+ super (SerializerMethodResourceRelatedField , self ).__init__ (* args , ** kwargs )
196200
197201 @classmethod
198202 def many_init (cls , * args , ** kwargs ):
199- list_kwargs = {'child_relation' : cls (* args , ** kwargs )}
203+ list_kwargs = {k : kwargs .pop (k ) for k in LINKS_PARAMS if k in kwargs }
204+ list_kwargs ['child_relation' ] = cls (* args , ** kwargs )
200205 for key in kwargs .keys ():
201206 if key in ('model' ,) + MANY_RELATION_KWARGS :
202207 list_kwargs [key ] = kwargs [key ]
@@ -211,10 +216,7 @@ def get_attribute(self, instance):
211216 return super (SerializerMethodResourceRelatedField , self ).get_attribute (instance )
212217
213218 def to_representation (self , value ):
214- if isinstance (value , QuerySet ):
219+ if isinstance (value , collections . Iterable ):
215220 base = super (SerializerMethodResourceRelatedField , self )
216221 return [base .to_representation (x ) for x in value ]
217- return super (SerializerMethodResourceRelatedField , self ).to_representation (value )
218-
219- def get_links (self , obj = None , lookup_field = 'pk' ):
220- return OrderedDict ()
222+ return super (SerializerMethodResourceRelatedField , self ).to_representation (value )
0 commit comments