Serialize request through django-rest-framework

I am trying to use an updated version of DRF. I used the code from the tutorial

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

I have to 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 to get the results right?

+4
source share
2 answers

if you need valid json you can do

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

The 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 OrderedDict.

According to the docs ,

- , , . , .

, python, dict() on serializer.data Kevin.

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

All Articles