Last active
December 26, 2015 02:09
-
-
Save ssfrr/7076289 to your computer and use it in GitHub Desktop.
serializer with custom collection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Doppel2Serializer(serializers.HyperlinkedModelSerializer): | |
@property | |
def data(self): | |
'''If a collection was requested (self.many is True), then we want to | |
return the full collection resource, including its own URL. This is | |
mostly cribbed from the BaseSerializer definition''' | |
if self._data is None: | |
obj = self.object | |
if self.many: | |
self._data = [self.to_native(item) for item in obj] | |
view_name = self.opts.model._meta.object_name.lower() + '-list' | |
data = { | |
'_href': reverse(view_name, | |
request=self.context['request']), | |
'_type': 'resource-list', | |
'data': self._data, | |
} | |
return data | |
else: | |
self._data = self.to_native(obj) | |
return self._data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment