编程语言
首页 > 编程语言> > [Python自学] restframework

[Python自学] restframework

作者:互联网

一、数据序列化的几种方式

在Django的视图函数中,我们从数据库中获取数据,由以下几种方式将其序列化成JSON数据:

1.方式一

class PublishView(View):
    def get(self, request):
        publish_list = list(Publish.objects.all().values())
        return HttpResponse(json.dumps(publish_list))

通过list强转的方式。

2.方式二

class PublishView(View):
    def get(self, request):
        publish_list = Publish.objects.all()
        temp = []
        for obj in publish_list:
            temp.append({
                'id': obj.id,
                'name': obj.name,
                'email': obj.email
            })

        return HttpResponse(json.dumps(temp))

通过字段拼接的方式。

使用model_to_dict方法来将对象转换成字典:

class PublishView(View):
    def get(self, request):
        from django.forms.models import model_to_dict
        publish_list = Publish.objects.all()
        temp = []
        for obj in publish_list:
            temp.append(model_to_dict(obj))

        return HttpResponse(json.dumps(temp))

3.方式三

利用django中的序列化组件:·

class PublishView(View):
    def get(self, request):
        from django.core import serializers
        publish_list = Publish.objects.all()
        ret = serializers.serialize("json", publish_list)

        return HttpResponse(ret)

4.方式四

利用restframework中的serializer:

from rest_framework import serializers


class PublishSerializers(serializers.Serializer):
    name = serializers.CharField()
    email = serializers.EmailField()


class PublishView(View):
    def get(self, request):
        publish_list = Publish.objects.all()

        ps = PublishSerializers(publish_list, many=True)

        return HttpResponse(ps.data)

这种方式的前提是安装djangorestframework。

 

二、安装restframe

pip install djangorestframework

 

三、

标签:serializers,temp,Python,list,publish,restframework,obj,自学,class
来源: https://www.cnblogs.com/leokale-zz/p/12228597.html