Skip to content

Instantly share code, notes, and snippets.

@alexhayes
Created February 25, 2016 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexhayes/af7ade8a52d2f70ba582 to your computer and use it in GitHub Desktop.
Save alexhayes/af7ade8a52d2f70ba582 to your computer and use it in GitHub Desktop.
class OrderedDictSerializer(serializers.ListSerializer):
"""
django-rest-framework serializer that a list or queryset into an OrderedDict.
"""
def to_representation(self, data):
"""
OrderedDict of object instances -> OrderedDict of dicts of primitive datatypes.
"""
# Dealing with nested relationships, data can be a Manager,
# so, first get a queryset from the Manager if needed
if isinstance(data, models.Manager):
return OrderedDict([
(item.pk, self.child.to_representation(item)) for item in data.all()
])
else:
return OrderedDict([
(key, self.child.to_representation(item)) for key, item in data.items()
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment