django Rest Framework----序列化

一、手动序列化

class BookView(APIView):
    '''
        构建数据结构
        [{"title": "go"}, {"title": "java"}, {"title": "python"}, {"title": "c++"}]
    '''
    def get(self,request):
        book_list = models.Book.objects.all()
        tmp=[]
        for book_obj in book_list:
            tmp.append({
                'title':book_obj.title
            })

        return HttpResponse(json.dumps(tmp))

    def post(self,request):
        return HttpResponse('post....')

model_to_dict():将对象转化成字典的形式:

[{"id": 1, "title": "go"}, {"id": 2, "title": "java"}, {"id": 3, "title": "python"}, {"id": 4, "title": "c++"}]

from django.forms.models import model_to_dict
class BookView(APIView):
    def get(self,request):
        book_list = models.Book.objects.all()
        tmp=[]
        for book_obj in book_list:
            tmp.append(model_to_dict(book_obj))

        return HttpResponse(json.dumps(tmp))

mode_to_dict()还支持一些参数:

def model_to_dict(instance, fields=None, exclude=None):
    pass

instance:queryset中每一个实例对象
fields:表示一个可选列表,如果提供则返回的dict中将只包含指定的字段
exclude:如果提供,则将字段排除在返回的dict中,即使fields包含它

二、使用django中的serialize

serialize的优点:它可以对queryset进行序列化。

序列化后的结果:
[{"model": "bookmanage.book", "pk": 1, "fields": {"title": "go"}}, {"model": "bookmanage.book", "pk": 2, "fields": {"title": "java"}}, {"model": "bookmanage.book", "pk": 3, "fields": {"title": "python"}}, {"model": "bookmanage.book", "pk": 4, "fields": {"title": "c++"}}]
from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from bookmanage import models
from django.core.serializers import serialize

class BookView(APIView):
def get(self,request): result = serialize('json',models.Book.objects.all()) return HttpResponse(result)

serialize:提供了将django模型翻译成其他格式的机制,serialize函数的参数是序列化数据的格式(请参阅序列化格式)和 QuerySet序列化。

三、使用REST框架序列化

使用REST框架序列化优点:可以把queryset序列化,也支持反序列化成queryset

创建Serializer类

首先我们需要提供一种序列化和反序列化

posted @ 2018-06-19 13:45  短毛兔  阅读(233)  评论(0编辑  收藏  举报