rest_framework 自己写的抽取基类

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from app01.myserialize import BookSerialize
from app01.models import Book,Author
# Create your views here.


# 抽的第一层
class List:   
    model = Book.objects.all()
    def lis(self, request):
        response = {"status": 100, "msg": "查看所有"}
        all_list = self.model
        ser = self.Ser(all_list, many=True)
        response["data"] = ser.data  # 序列化以后的数据在data里
        return Response(response)

    def create(self,request):
        response = {"status": 100, "msg": "插入成功"}
        try:
            book_ser = self.Ser(data=request.data)
            if book_ser.is_valid():
                book_ser.save()
                response['data'] = book_ser.data
            else:
                response['msg'] = book_ser.errors
        except Exception as e:
            response['msg'] = str(e)
        return Response(response)

    def fetch(self, request, pk, *args, **kwargs):
        response = {"status": 100, "msg": "查看单条"}
        book = self.model.filter(nid=pk).first()
        ser = self.Ser(book, many=False)
        response["data"] = ser.data  # 序列化以后的数据在data里
        return Response(response)

    def remove(self,request, pk, *args, **kwargs):
        self.model.filter(nid=pk).delete()
        return Response("")

    def update(self, request, pk, *args, **kwargs):
        response = {"status": 100, "msg": "修改成功"}
        book_obj = self.model.filter(nid=pk).first()
        book_ser = self.Ser(data=request.data, instance=book_obj)  # 反序列化,指定要修改的数据库
        if book_ser.is_valid():
            book_ser.save()  # 修改数据库( rest_framework封装了代码 )
            response["data"] = book_ser.data
        else:
            response["error"] = book_ser.error_messages
        return Response(response)


class Books_cla(List):  # 第二层
    def get(self, request, *args, **kwargs):
        return self.lis(request)

    def post(self, request):
        return self.create(request)


class Book_cla(List):  # 第二层
    def get(self, request, pk, *args, **kwargs):
        return self.fetch(request, pk, *args, **kwargs)

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

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



class Books(Books_cla, APIView):
    Ser = BookSerialize

class BookView(Book_cla, APIView):
    Ser = BookSerialize

View Code

rest_framework 序列化组件 之 mixins,generics 类下增删改查类

url:

  url(r'^books/$', views.Books.as_view()),
  url(r'^books/(?P<pk>\d+)', views.BookView.as_view()),

视图层:

# 创建          # 查看所有        # 删除            # 修改            # 更新
from rest_framework.mixins import CreateModelMixin,ListModelMixin,DestroyModelMixin,RetrieveModelMixin,UpdateModelMixin
from rest_framework.generics import GenericAPIView


class Books(ListModelMixin,CreateModelMixin, GenericAPIView):  # 一定要继承GenericAPIView这个类
    queryset = Book.objects.all()  # 指定要序列化的数据
    serializer_class = BookSerialize  # 指定序列化的类
    # 查看所有
    def get(self, request, *args, **kwargs):
        return self.list(request)
    # 添加
    def post(self,request, *args, **kwargs):
        return self.create(request)




                    # 删除             # 更新        # 查看单条序列化
class BookView(DestroyModelMixin, UpdateModelMixin, RetrieveModelMixin, GenericAPIView):   # 一定要继承GenericAPIView这个类
    queryset = Book.objects.all()  # 指定要序列化的数据
    serializer_class = BookSerialize    # 序列化的对象

    # 查看单条序列化
    def get(self, request, *args, **kwargs):
        return self.retrieve(request)

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

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

 

rest_framework 序列化组件 generics 类下 ListCreateAPIView    ,   RetrieveUpdateDestroyAPIView   查/更新/删除

from rest_framework.generics import GenericAPIView,ListCreateAPIView,RetrieveUpdateDestroyAPIView

class BookView(ListCreateAPIView):  # 这个类封装了 查看所有和创建方法
    queryset = Book.objects.all()   # 指定要序列化的数据
    serializer_class = BookSerialize   # 序列化的对象

 

rest_framework 序列化组件 之 viewsets 类下增删改查类   (用的少,封装的太多了)

url:

 url(r'^books/$', views.BookView.as_view({"get": "list", "post": "create"})),
 url(r'^books/(?P<pk>\d+)', views.BookView.as_view({"get": "retrieve", "put": "update", "delete": "destroy"})),

视图:

from rest_framework.viewsets import ModelViewSet

class BookView(ModelViewSet):  # 继承了 ModelViewSet 这个类 增删改查方法都封装了
    queryset = Book.objects.all()   # 指定要序列化的数据
    serializer_class = BookSerialize   # 序列化的对象

 

rest_framework 序列化组件 之 viewsets类下的 ViewSetMixin 类  (推荐使用,在一个类写增删改查方法)

url:

url(r'^books/$', views.BookView.as_view({"get": "a", "post": "b"})),

视图层:

from rest_framework.viewsets import ViewSetMixin
from rest_framework.views import APIView
      # ViewSetMixin这个类要写在前面
class BookView(ViewSetMixin,APIView):  # 在一个类写增删改查方法
    def a(self,request):
        return HttpResponse("aok")

    def b(self,request):
        return HttpResponse("bok")

 

版权声明:本文为liu--huan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/liu--huan/p/10609952.html