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/
- [Django]-Django-summernote image upload
- [Django]-Django DB Design β Maintaining common and historical data
- [Django]-Django URLResolver error
- [Django]-CSS file not found. Django project
- [Django]-Django admin with websocket
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
- [Django]-Django aggregation over annotated query
- [Django]-Issue with returning Cyrillic symbols from MSSQL via unixODBC and FreeTDS
- [Django]-Python: Element order in dictionary
- [Django]-Django sites framework and Heroku
- [Django]-Django clean-up code