DRF序列化程序 - OrderDict而不是JSON

时间:2017-05-17 10:11:09

标签: django django-serializer

我是Django1.9的新手,

models.py: -

class MyUser(models.Model):

    UserId = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    UserFirstName = models.CharField(max_length=1000)
    UserLastName = models.CharField(max_length=1000)
    UserEmail = models.EmailField(max_length=1000,blank=False,null=True)
    UserContactNumber = models.CharField(max_length=1000)
    UserPassword = models.CharField(max_length=1000)
    IsActive = models.BooleanField(default=False)
    Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True)

    class Meta:
        ordering =('IsActive',)

serializers.py: -

class MyUserSerializer(serializers.ModelSerializer):

    class Meta:
        model = MyUser
        fields = '__all__'

Shell输出: -

>>> from projectmanagement.serializers import MyUserSerializer
>>> users = MyUser.objects.all()
>>> users
[<MyUser: MyUser object>, <MyUser: MyUser object>]
>>> serializer = MyUserSerializer(users,many=True)
>>> serializer
MyUserSerializer([<MyUser: MyUser object>, <MyUser: MyUser object>], many=True):
    UserId = UUIDField(label='UserId', read_only=True)
    UserFirstName = CharField(label='UserFirstName', max_length=1000)
    UserLastName = CharField(label='UserLastName', max_length=1000)
    UserEmail = EmailField(allow_null=True, label='UserEmail', max_length=1000, required=False)
    UserContactNumber = CharField(label='UserContactNumber', max_length=1000)
    UserPassword = CharField(label='UserPassword', max_length=1000)
    IsActive = BooleanField(label='IsActive', required=False)
    Role = ListField(allow_null=True, child=CharField(label='Role', max_length=1000), required=False)
>>> serializer.data
[OrderedDict([('UserId', 'fd5df8d3-a578-4fe7-95ea-172ad2399ff8'), ('UserFirstName', u''), ('UserLastName', u''), ('UserEmail', None), ('UserContactNumber', u''), ('UserPassword', u''), ('IsActive', False), ('Role', None)]), OrderedDict([('UserId', '8301e1b6-a031-443f-957a-df98025e5e9f'), ('UserFirstName', u'Piyush'), ('UserLastName', u'Wanare'), ('UserEmail', u'piyush@uniserved.com'), ('UserContactNumber', u'992053268236'), ('UserPassword', u'Piyush@1234'), ('IsActive', True), ('Role', [u'Vendor Cordinator'])])]

为什么我没有获得JSON数据而不是OrderedDict? 如何以JSON格式获取数据?

4 个答案:

答案 0 :(得分:4)

我猜您使用的是Django REST Framework?

在DRF的TutorialAPI Guide中没有详细记录。但是,实际上在 Tutorial 1: Serialization 中提供了序列化查询集的示例:

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')])]

以JSON格式获取数据:

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

答案 1 :(得分:1)

您需要先将响应序列化为JSON。

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)

请参阅:https://docs.djangoproject.com/en/1.9/topics/serialization/#serialization-formats-json

如果你的最终目标是将其作为HTTP响应,那么你也可以使用它:https://docs.djangoproject.com/en/1.9/ref/request-response/#jsonresponse-objects

还尝试升级到Django 1.11,因为不再支持1.9。点击此处查看如何升级:https://docs.djangoproject.com/en/1.11/howto/upgrade-version/

答案 2 :(得分:1)

您好,您可以使用序列化器:

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

文档在这里:https://docs.djangoproject.com/en/1.9/topics/serialization/

但是请升级到1.11,1.9是不安全的版本

使用DRF,serializers.ModelSerializer默认执行此作业,因此最好安装它:http://www.django-rest-framework.org/

答案 3 :(得分:0)

只需将这段代码放在setting.py文件中

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

并通过以下方式获取JSON数据

serializer.data