REST framework视图(APIView视图与generic与mixins视图)

一、基于APIView类的视图用法

  定义序列化器:

from .models import *
from django.shortcuts import HttpResponse
from django.core import serializers

# 序列化器
from rest_framework import serializers

# 书籍序列化器
class BookSerializers(serializers.ModelSerializer):
      class Meta:
          model=Book
          fields="__all__"
          #depth=1 # 序列化深度

# 出版社序列化器
class PublshSerializers(serializers.ModelSerializer):

      class Meta:
          model=Publish
          fields="__all__"
          depth=1

  定义视图函数类:


from rest_framework.views import APIView
from rest_framework.response import Response


# 书籍视图
class
BookViewSet(APIView):    # 获取数据 def get(self,request,*args,**kwargs): book_list=Book.objects.all() bs=BookSerializers(book_list,many=True,context={'request': request}) # many=True获取多条(全部)数据 return Response(bs.data)    # 创建数据 def post(self,request,*args,**kwargs): print(request.data) # 获取form表单提交数据 bs=BookSerializers(data=request.data,many=False) # 数据校验 if bs.is_valid(): print(bs.validated_data) # 获取校验后的数据 bs.save() # 数据保存 return Response(bs.data) else: return HttpResponse(bs.errors) # 返回API错误信息 # 书籍详细视图(带pk值),单条数据 class BookDetailViewSet(APIView):    # 获取单条数据 def get(self,request,pk): book_obj=Book.objects.filter(pk=pk).first() bs=BookSerializers(instance=book_obj,context={'request': request}) # context上下文数据 return Response(bs.data)      # 更新单条数据 def put(self,request,pk): book_obj=Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,data=request.data,context={'request': request}) if bs.is_valid(): bs.save() return Response(bs.data) else: return HttpResponse(bs.errors) # 出版社视图 class PublishViewSet(APIView):   # 获取所有出版社信息 def get(self,request,*args,**kwargs): publish_list=Publish.objects.all() bs=PublshSerializers(publish_list,many=True,context={'request': request}) return Response(bs.data)      # 创建新出版社信息 def post(self,request,*args,**kwargs): bs=PublshSerializers(data=request.data,many=False) if bs.is_valid(): # print(bs.validated_data) bs.save() return Response(bs.data) else: return HttpResponse(bs.errors) # 出版社详细信息 class PublishDetailViewSet(APIView): # 获取单条信息 def get(self,request,pk): publish_obj=Publish.objects.filter(pk=pk).first() bs=PublshSerializers(instance=publish_obj,context={'request': request}) return Response(bs.data)
# 更新数据
def put(self,request,pk): publish_obj=Publish.objects.filter(pk=pk).first() bs=PublshSerializers(instance=publish_obj,data=request.data,context={'request': request}) if bs.is_valid(): bs.save() return Response(bs.data) else: return HttpResponse(bs.errors)

二、基于mixins类的视图用法

  路由分发urls.py

from django.contrib import admin
from django.urls import path, re_path
from .views import mixin

urlpatterns = [
    # 书籍信息
    re_path(r"^book/$", mixin.BookViewSet.as_view())
    # 书籍详情页
    re_path(r"^book/(?P<pk>\d+)/$", mixin.BookDetailViewSet.as_view())

]

  通过使用mixin类编写视图:

from rest_framework import mixins
from rest_framework import generics

# 书籍视图类
class BookViewSet(mixins.ListModelMixin, # 获取所有数据 mixins.CreateModelMixin, # 创建数据 generics.GenericAPIView): # 继承GenericAPIView类    queryset = Book.objects.all() serializer_class = BookSerializers # 定义的序列化器
   # 重写父类get方法
def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs)
   # 重写父类post方法
def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) # 书籍的详情页 class BookDetailViewSet(mixins.RetrieveModelMixin, # 获取单条数据 mixins.UpdateModelMixin, # 更新数据 mixins.DestroyModelMixin, # 删除单条数据 generics.GenericAPIView):

  lookup_field = "pk"
  lookup_url_kwarg = None
   queryset
= Book.objects.all() serializer_class = BookSerializers
   # 获取数据,重写父类的get方法
def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs)
   # 更新数据,重写父类的put方法
def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs)
# 删除数据,重写父类的delete方法
def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs)

三、基于generic类的视图用法

  通过使用mixin类,我们使用更少的代码重写了这些视图,但我们还可以再进一步。REST框架提供了一组已经混合好(mixed-in)的通用视图,我们可以使用它来简化我们的views.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

 

posted @ 2019-08-05 21:53  WiseAdministrator  阅读(189)  评论(0编辑  收藏  举报