Created
February 25, 2016 01:20
-
-
Save alexhayes/af7ade8a52d2f70ba582 to your computer and use it in GitHub Desktop.
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 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