首页 > 其他分享 >【Django-rest-framework框架】第04回 视图集

【Django-rest-framework框架】第04回 视图集

时间:2022-09-30 19:22:42浏览次数:53  
标签:return ser 04 get self request rest Django class

目录

1. 两个视图基类

1.1 GenericAPIview属性和方法

属性:
    serializer_class:指明视图使用的序列化器
方法:
    get_serializer_class(self):获取序列化类
    get_serializer(self,*args,*kwargs):该方法在提供序列化器对象的时候,会向序列化器对象的context属性补充三个数据:request、format、view,这三个数据对象可以在定义序列化器时使用。
        request 当前视图的请求对象
        view 当前请求的类视图对象
        format 当前请求期望返回的数据格式
属性:
    quesyset:指明使用的数据查询集
方法:
    get_queryset(self):获取序列化数据
    get_objest(self):根据lookup_field配置的参数获取单个对象

1. lookup_field  # 通过get_object  获取单个对象的查询key值,value值是路由中传进来的
2. filter_backends  # 过滤类
3. pagination_class # 分页类

1.2 基于APIView写5个接口

from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from .models import User
from rest_framework.response import Response
from .serializer import UserSerializer


class UserView(APIView):
    def get(self, request):
        user_list = User.objects.all()
        ser = UserSerializer(instance=user_list, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = UserSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'}, status=201)
        else:
            return Response({'code': 101, 'msg': ser.errors})


class UserDetailView(APIView):
    def get(self, request, pk):
        user = User.objects.filter(pk=pk).first()
        ser = UserSerializer(instance=user)
        return Response(ser.data)

    def put(self, request, pk):
        user = User.objects.filter(pk=pk).first()
        ser = UserSerializer(instance=user, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功'}, status=201)
        else:
            return Response({'code': 100, 'msg': ser.errors})

    def delete(self, request, pk):
        User.objects.filter(pk=pk).delete()
        return Response('')

1.3 基于GenericAPIview写5个接口

from rest_framework.generics import GenericAPIView

class UserView(GenericAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    def get(self, request):
        user_list = self.get_queryset()
        ser = self.get_serializer(instance=user_list, many=True)
        return Response(ser.data)

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '新增成功'}, status=201)
        else:
            return Response({'code': 101, 'msg': ser.errors})


class UserDetailView(GenericAPIView):
    queryset = User.objects.all()
    serializer_class =  UserSerializer
    def get(self, request, pk):
        user = self.get_object()
        ser = self.get_serializer(instance=user)
        return Response(ser.data)

    def put(self, request, pk):
        user = self.get_object()
        ser = self.get_serializer(instance=user, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 100, 'msg': '修改成功'}, status=201)
        else:
            return Response({'code': 100, 'msg': ser.errors})

    def delete(self, request, pk):
        self.get_queryset().filter(pk=pk).delete()
        return Response('')

2. 5个视图扩展类

必须配合GenericAPIView使用,不能配合APIView使用

CreateModelMixin:写了一个Create方法,就是原来咱们post中的代码
RetrieveModelMixin:retrieve,就是咱们原来的get
UpdateModelMixin:update方法,就是咱们原来的put
ListModelMixin:list方法,就是原来咱们的get
DestroyModelMixin:destroy方法,就是原来咱们的delete

list() 提供一组数据
retrieve() 提供单个数据
create() 创建数据
update() 保存数据
destory() 删除数据
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import RetrieveModelMixin, CreateModelMixin, UpdateModelMixin, DestroyModelMixin, \
    ListModelMixin


class UserView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    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 UserDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    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)

3. 9个视图子类

视图类:继承GenericAPIView+某个或某几个视图扩展类

from rest_framework.generics import ListAPIView,CreateAPIView,   RetrieveAPIView,DestroyAPIView,UpdateAPIView
from rest_framework.generics import ListCreateAPIView,     RetrieveUpdateDestroyAPIView,RetrieveUpdateAPIView,RetrieveDestroyAPIView
正常来讲  Destroy+Update 应该有一个,作者没加,可能没有应用场景
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, DestroyAPIView, UpdateAPIView
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView, RetrieveUpdateAPIView, \
    RetrieveDestroyAPIView


class UserView(ListCreateAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetailView(RetrieveUpdateDestroyAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

4. 视图集

继承ModelViewSet编写5个接口

视图类
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
class UserView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
路由
path('user/', views.UserView.as_view({'get': 'list', 'post': 'create'})),
path('user/<int:pk>', views.UserView.as_view({'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

5. 源码分析ViewSetMixin

@classonlymethod
def as_view(cls, actions=None, **initkwargs):
    # 路由中as_view中必须传参数,必须传字典:{'get': 'list', 'post': 'create'}
    if not actions: 
        raise TypeError("The `actions` argument must be provided when "
                        "calling `.as_view()` on a ViewSet. For example "
                        "`.as_view({'get': 'list'})`")
	# 路由匹配成功,执行view(request),request是老的request
    def view(request, *args, **kwargs):
	    # actions={'get': 'list', 'post': 'create'}
        for method, action in actions.items():
            # method:get      action:list
            # self 是视图类的对象中通过反射,查找list,
            # handler视图类中的list方法
            handler = getattr(self, action)
            # 向视图类的对象中,反射 method:get,handler:list方法
            # self.get=list
            setattr(self, method, handler)
        return self.dispatch(request, *args, **kwargs)
    return csrf_exempt(view)



1. 只要继承了ViewSetMixin,以后路由写法变量,都要协程:views.UserView.as_view({'get': 'list', 'post': 'create'}))
2. 这样写好以后,对应的请求方式来了,就会执行配置的方法
3. 以后只要继承了ViewSetMixin,视图类中可以写任意名字的方法,不用非得写get,post,delete

6. 总结


#两个基类
APIView
GenericAPIView:有关数据库操作,queryset 和serializer_class


#5个视图扩展类(rest_framework.mixins)
CreateModelMixin:create方法创建一条
DestroyModelMixin:destory方法删除一条
ListModelMixin:list方法获取所有
RetrieveModelMixin:retrieve获取一条
UpdateModelMixin:update修改一条

#9个子类视图(rest_framework.generics)
CreateAPIView:继承CreateModelMixin,GenericAPIView,有post方法,新增数据
DestroyAPIView:继承DestroyModelMixin,GenericAPIView,有delete方法,删除数据
ListAPIView:继承ListModelMixin,GenericAPIView,有get方法获取所有
UpdateAPIView:继承UpdateModelMixin,GenericAPIView,有put和patch方法,修改数据
RetrieveAPIView:继承RetrieveModelMixin,GenericAPIView,有get方法,获取一条


ListCreateAPIView:继承ListModelMixin,CreateModelMixin,GenericAPIView,有get获取所有,post方法新增
RetrieveDestroyAPIView:继承RetrieveModelMixin,DestroyModelMixin,GenericAPIView,有get方法获取一条,delete方法删除
RetrieveUpdateAPIView:继承RetrieveModelMixin,UpdateModelMixin,GenericAPIView,有get获取一条,put,patch修改
RetrieveUpdateDestroyAPIView:继承RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView,有get获取一条,put,patch修改,delete删除

#视图集
ViewSetMixin:重写了as_view 
ViewSet:     继承ViewSetMixin和APIView

GenericViewSet:继承ViewSetMixin, generics.GenericAPIView
ModelViewSet:继承mixins.CreateModelMixin,mixins.RetrieveModelMixin,mixins.UpdateModelMixin,mixins.DestroyModelMixin,mixins.ListModelMixin,GenericViewSet
ReadOnlyModelViewSet:继承mixins.RetrieveModelMixin,mixins.ListModelMixin,GenericViewSet

7 继承关系画出来,有哪些常用属性或方法写出来

标签:return,ser,04,get,self,request,rest,Django,class
From: https://www.cnblogs.com/cainiaozhy/p/16745896.html

相关文章