一、django框架的序列化 直接上代碼 1、這是app下的models.py 2、這是app下的view.py,兩種序列化方法 總結: 我們會發現序列化出來的數據比較單一,返回來的樣式太麻煩,而django自帶的方法,而且無法反序列化! 二、rest_framework中的序列化組件 首先我們要先 ...
一、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"})),
]