[Django]-DRF Serializer – OrderDict instead of JSON

11πŸ‘

I guess you are using Django REST Framework?

It’s not well-documented in the DRF’s Tutorial or API Guide. But example is actually given in Tutorial 1: Serialization for serializing a queryset:

serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [OrderedDict([('id', 1), ('title', u''), ('code', u'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', u''), ('code', u'print "hello, world"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', u''), ('code', u'print "hello, world"'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])]

To get data in JSON format:

import json
serializer = MyUserSerializer(users,many=True)
json.dumps(serializer.data)

2πŸ‘

You need to serialize the response as a JSON first.

from django.utils.encoding import force_text
from django.core.serializers.json import DjangoJSONEncoder

class LazyEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, YourCustomType):
            return force_text(obj)
        return super(LazyEncoder, self).default(obj)

See: https://docs.djangoproject.com/en/1.9/topics/serialization/#serialization-formats-json

And if your end goal is to do it as an HTTP response, you can also use this: https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects

Also try to upgrade to Django 1.11 as 1.9 is no longer supported. Check here on how to upgrade: https://docs.djangoproject.com/en/1.11/howto/upgrade-version/

1πŸ‘

Hi you can use serializers :

from django.core import serializers
data = serializers.serialize("json", MyUser.objects.all())

The doc is here : https://docs.djangoproject.com/en/1.9/topics/serialization/

But please upgrade to 1.11, 1.9 is insecure version

With DRF, serializers.ModelSerializer do the job by default, so it’s a good idea to install it : http://www.django-rest-framework.org/

0πŸ‘

Simply just put this code in setting.py file

REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
    'rest_framework.parsers.JSONParser',
]}

And get your JSON data by

serializer.data

Leave a comment