Skip to content

Instantly share code, notes, and snippets.

@ssfrr
Last active December 26, 2015 02:09
Show Gist options
  • Save ssfrr/7076289 to your computer and use it in GitHub Desktop.
Save ssfrr/7076289 to your computer and use it in GitHub Desktop.
serializer with custom collection
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