AlexYar
AlexYar

Reputation: 99

serialize queryset via django-rest-framework

I try to use updating version of DRF. I used code from tutorial

serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data

I should get

[{
  'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 
  'language': u'python', 'style': u'friendly'
 }, {
  'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 
  'language': u'python', 'style': u'friendly'
}]

but I got:

[OrderedDict([
  ('pk', 1), ('title', u''), ('code', u'foo = "bar"\n'), 
  ('linenos', False), ('language', 'python'), ('style', 'friendly')
 ]), 
 OrderedDict([
  ('pk', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), 
  ('language', 'python'), ('style', 'friendly')
 ])
]

Please explain how get correctly results?

Upvotes: 4

Views: 3363

Answers (2)

Sergei
Sergei

Reputation: 89

if you need valid json, you can do

import json
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
json.dumps(serializer.data)

Upvotes: 3

Rahul Gupta
Rahul Gupta

Reputation: 47886

Results are correct. DRF explicitly uses OrderedDict in the serialization process.

OrderedDict:

OrderedDict is a subclass of dict. You can perform all the operations of a normal python dictionary on an OrderedDict.

As per the docs,

Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.

Also, if you need a regular python dictionary, you can use dict() on serializer.data as Kevin also suggested.

dict(serializer.data)  # Converts to regular python dict

Upvotes: 1

Related Questions