淘先锋技术网

首页 1 2 3 4 5 6 7

一、django框架的序列化

直接上代码

1、这是app下的models.py

from django.db import models

# Create your models here.



class Course(models.Model):
    title=models.CharField(max_length=32)

2、这是app下的view.py,两种序列化方法

from django.views import View
from app01.models import Course


class CourseView(View):

    def get(self,request):

        ret=Course.objects.all()
        #这是我们自己用json模块去序列化数据
        #import json
        #temp=[] 
        # for i in ret:
        #     temp.append({
        #         "title":i.title
        #    })

        #这是django自带的
         from django.core.serializers import serialize
         ret=serialize("json",ret)

         # return HttpResponse(temp)     
         return HttpResponse(ret)

总结:

  我们会发现序列化出来的数据比较单一,返回来的样式太麻烦,而django自带的方法,而且无法反序列化!

二、rest_framework中的序列化组件

 首先我们要先下载这个模块

pip3 install djangorestframework

装好之后,不要忘了在app中注册rest_framework,

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from django.shortcuts import HttpResponsefrom rest_framework import serializers

class BookSerializers(serializers.Serializer):  
    title=serializers.CharField(max_length=32)
    price=serializers.IntegerField()
    pub_date=serializers.DateField()
    publish=serializers.CharField(source="publish.name")
    #authors=serializers.CharField(source="authors.all")
    authors=serializers.SerializerMethodField()
    def get_authors(self,obj):
        temp=[]
        for author in obj.authors.all():
            data=[]
       data.append(author.pk) 
       data.append(author.name)
       temp.append(data)
return temp class BookViewSet(APIView): def get(self,request,*args,**kwargs): book_list=Book.objects.all() bs=BookSerializers(book_list,many=True) return Response(bs.data)

我们这里有更简便的方法:

from rest_framework import serializers
from app01.models import Book
class BookSerializers(serializers.ModelSerializer):
    class Meta:
        model=Book
        fields="__all__"

 五种状态的标准形式

class BookView(APIView):

    def get(self, request):
        book_list = Book.objects.all()
        bs = BookSerializers(book_list, many=True)
        # 序列化数据
        return Response(bs.data)

    def post(self, request):
        # 添加一条数据
        print(request.data)
        bs=BookSerializers(data=request.data)
        if bs.is_valid():
            bs.save()  # 生成记录
            return Response(bs.data)
        else:
            return Response(bs.errors)

class BookDetailView(APIView):
    def get(self,request,pk):
        book_obj=Book.objects.filter(pk=pk).first()
        bs=BookSerializers(book_obj,many=False)
        return Response(bs.data)

    def put(self,request,pk):
        book_obj = Book.objects.filter(pk=pk).first()
        bs=BookSerializers(data=request.data,instance=book_obj)#instance
        if bs.is_valid():
            bs.save() # update
            return Response(bs.data)
        else:
            return Response(bs.errors)

    def delete(self,request,pk):
        Book.objects.filter(pk=pk).delete()
        return Response("")

我们再创建一张表,我们会发现代码有点冗余了,除了变量名的变化,这里也有封好的方法mixin类

from rest_framework import mixins
from rest_framework import generics

class BookViewSet(mixins.ListModelMixin,
                  mixins.CreateModelMixin,
                  generics.GenericAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)



class BookDetailViewSet(mixins.RetrieveModelMixin,
                    mixins.UpdateModelMixin,
                    mixins.DestroyModelMixin,
                    generics.GenericAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

我们在上面的几个类中,我们下来翻看源码:

from rest_framework.mixins import CreateModelMixin
from rest_framework.mixins import ListModelMixin
from rest_framework.mixins import DestroyModelMixin
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.mixins import UpdateModelMixin

我们先来看CreateModeMixin类的源码,我们发现 create 

ListModeMixin类的源码,我们发现list

 

RetrieveModelMixin类的源码,我们发现retrieve

UpdateModelMixin类的源码,我们发现update

 

DestroyModelMixin类的源码,我们发现destroy

然后我们可以这样封装:

from rest_framework.mixins import CreateModelMixin,ListModelMixin,DestroyModelMixin,RetrieveModelMixin,UpdateModelMixin
from rest_framework import generics

class BookView(CreateModelMixin,ListModelMixin,generics.GenericAPIView,):

    queryset=Book.objects.all()
    serializer_class=BookSerializers

    def get(self,request):
        return self.list(request)

    def post(self,request):

        return self.create(request)

class BookDetailView(DestroyModelMixin,UpdateModelMixin,RetrieveModelMixin,generics.GenericAPIView,):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

    def get(self,request, *args, **kwargs):

       return self.retrieve(request, *args, **kwargs)

    def put(self,request, *args, **kwargs):

       return self.update(request, *args, **kwargs)

    def delete(self,request, *args, **kwargs):

        return self.destroy(request, *args, **kwargs)

发现代码还是冗余的,我们还有更简便的方法,REST框架提供了简化的view.py模块

from rest_framework import mixins
from rest_framework import generics

class BookViewSet(generics.ListCreateAPIView):

    queryset = Book.objects.all()
    serializer_class = BookSerializers

class BookDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializers

class PublishViewSet(generics.ListCreateAPIView):

    queryset = Publish.objects.all()
    serializer_class = PublshSerializers

class PublishDetailViewSet(generics.RetrieveUpdateDestroyAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublshSerializers

需要什么样的方法,就继承什么方法类,但里面的方法需要在url传入需要的参数

#views中代码非常简介,最重要的还是urls
from rest_framework.viewsets import ModelViewSet

class AuthorModelView(ModelViewSet):

    queryset=Author.objects.all()
    serializer_class=AuthorSerializers
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    #在as_view中加入参数
    url(r'^authors/$', views.AuthorModelView.as_view({"get":"list","post":"create"})),
    url(r'^authors/(?P<pk>\d )/$', views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
]

 


更多专业前端知识,请上 【猿2048】www.mk2048.com