首页 > 其他分享 >9.视图

9.视图

时间:2022-11-16 10:11:08浏览次数:45  
标签:rest framework 视图 UserInfo import class GenericViewSet

在视图中,如果参数有request,我们可以直接使用,如果参数没有,则可以通过self.request获取

 1.APIView

我们之前使用的基本上都是APIView,给我们提供了免除csrf验证,请求封装,版本控制,认证,权限和限流的功能,以下是源码展示

 

 

 

2.GenericAPIView

GenericAPIView 继承了APIView,增加了一些功能,如get_queryset,get_object等,实际开发中我们不会直接继承该类,该类是为后续的高度封装做的准备

 

 

 

3.GenericViewSet

开发中一般也很少直接去继承他,因为他也属于是 中间人类,在原来 GenericAPIView 基础上又增加了一个映射而已

 

 

 

 

 

 

GenericViewSet类中没有定义任何代码,他就是继承 ViewSetMixinGenericAPIView,也就说他的功能就是将继承的两个类的功能继承到一起。

  • GenericAPIView,将数据库查询、序列化类的定义提取到类变量中,便于后期处理。

  • ViewSetMixin,将 get/post/put/delete 等方法映射到 list、create、retrieve、update、partial_update、destroy方法中,让视图不再需要两个类。

# urls.py

from django.urls import path, re_path, include
from app01 import views

urlpatterns = [
    path('api/users/', views.UserView.as_view({"get":"list","post":"create"})),
    path('api/users/<int:pk>/', views.UserView.as_view({"get":"retrieve","put":"update","patch":"partial_update","delete":"destory"})),
]
# views.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response

    
class UserView(GenericViewSet):
    
    # 认证、权限、限流等
    queryset = models.UserInfo.objects.filter(status=True)
    serializer_class = 序列化类
    
    def list(self, request):
        # 业务逻辑:查看列表
        queryset = self.get_queryset()
        ser = self.get_serializer(intance=queryset,many=True)
        print(ser.data)
        return Response({"code": 0, 'data': "..."})

    def create(self, request):
        # 业务逻辑:新建
        return Response({'code': 0, 'data': "..."})
    
    def retrieve(self, request,pk):
        # 业务逻辑:查看某个数据的详细
        return Response({"code": 0, 'data': "..."})

    def update(self, request,pk):
        # 业务逻辑:全部修改
        return Response({'code': 0, 'data': "..."})
    
    def partial_update(self, request,pk):
        # 业务逻辑:局部修改
        return Response({'code': 0, 'data': "..."})
    
    def destory(self, request,pk):
        # 业务逻辑:删除
        return Response({'code': 0, 'data': "..."})

 

4.五大视图类

助我们封装了增删改查查常用的的5个接口,结合着GenericViewSet使用

4.1 ListModelMixin

查看数据列表

 

 

 

路由

from django.urls import path
from app01 import views

urlpatterns = [
    path('api/user/', views.User.as_view({'get': 'list'})),
]

视图

from app01.models import UserInfo
from rest_framework import serializers
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, \
    RetrieveModelMixin, \
    CreateModelMixin, \
    UpdateModelMixin, \
    DestroyModelMixin


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['username', 'age', 'email']


class User(ListModelMixin, GenericViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserModelSerializer

 

4.2 RetrieveModelMixin

查看指定数据

 

 

 路由

urlpatterns = [
    path('api/user/<int:pk>/', views.User.as_view({'get': 'retrieve'})),
]

视图

from app01.models import UserInfo
from rest_framework import serializers
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, \
    RetrieveModelMixin, \
    CreateModelMixin, \
    UpdateModelMixin, \
    DestroyModelMixin


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['username', 'age', 'email']


class User(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserModelSerializer

 

4.3 CreateModelMixin

创建数据

我们在保存数据到数据库中,可能前端传过来的数据只是部分,我们还需要对其他字段进行指定,可以重写perform_create

 

 

 路由

urlpatterns = [
    path('api/user/', views.User.as_view({'get': 'list', 'post': 'create'})),
]

视图

from app01.models import UserInfo
from rest_framework import serializers
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, \
    RetrieveModelMixin, \
    CreateModelMixin, \
    UpdateModelMixin, \
    DestroyModelMixin


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['username', 'age', 'email']


class User(ListModelMixin, RetrieveModelMixin, CreateModelMixin, GenericViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserModelSerializer

    def perform_create(self, serializer):
        serializer.save(password="123")

 

4.4 DestroyModelMixin

删除数据

 

 

 路由

urlpatterns = [
    path('api/user/<int:pk>/', views.User.as_view({'get': 'retrieve', 'delete': 'destroy'})),
]

视图

from app01.models import UserInfo
from rest_framework import serializers
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, \
    RetrieveModelMixin, \
    CreateModelMixin, \
    UpdateModelMixin, \
    DestroyModelMixin


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['username', 'age', 'email']


class User(ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, GenericViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserModelSerializer

 

4.5 UpdateModelMixin

  • 全部更新:对于序列化起中fields中非只读的字段必须都传递过来,进行更新

  • 局部更新:对于序列化中的fields中非只读的字段可以传递过来部分进行更新

 

 

 

路由

from django.urls import path
from app01 import views

urlpatterns = [
    path('api/user/', views.User.as_view({'get': 'list', 'post': 'create'})),
    path('api/user/<int:pk>/', views.User.as_view(
        {'get': 'retrieve',
         'delete': 'destroy',
         'put': 'update',
         'patch': 'partial_update'
         }
    )
         ),
]

视图

from app01.models import UserInfo
from rest_framework import serializers
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, \
    RetrieveModelMixin, \
    CreateModelMixin, \
    UpdateModelMixin, \
    DestroyModelMixin


class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ['username', 'age', 'email']


class User(ListModelMixin, RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, UpdateModelMixin, GenericViewSet):
    queryset = UserInfo.objects.all()
    serializer_class = UserModelSerializer

 

小结:

  • 接口与数据库操作无关,直接继承APIView

  • 接口背后需要对数据库进行操作,一般:ModelViewSetCreateModelMixin、ListModelMixin...

  • 利用钩子自定义功能。重写某个写方法,实现更加完善的功能。

标签:rest,framework,视图,UserInfo,import,class,GenericViewSet
From: https://www.cnblogs.com/victor1234/p/16892192.html

相关文章

  • 第08章 索引和视图
    在SQLServer中,设计有效的索引(Index)是影响数据库性能的重要因素之一,合理的索引可以显著提高数据库的查询性能。视图是一个虚拟表,视图中数据来源于由定义视图所引用的表,......
  • Prism通过反射机制自动注册对话视图模型
    摘要说明在使用WPF+Prism开发中,有时会需要使用到一些弹窗服务,而在Prism当中,我们使用Dialog是需要注入到IOC容器当中的,传统的写法如下:而当Dialog过多时或者需要新增一个......
  • MySQL视图
    准备工作,新建名为students的数据,三张表分别是student,courses,stu_cou,并创建外键约束,级联删除更新,插入数据。/*创建数据库*/createdatabaseifnotEXISTSstudentscha......
  • 视图层 View
    框架的视图层由WXML与WXSS编写,由组件来进行展示。将逻辑层的数据反映成视图,同时将视图层的事件发送给逻辑层。WXML(WeiXinMarkuplanguage)用于描述页面的结构。W......
  • 67.数据变了视图没变,怎么查找错误,怎么解决
    console.log()打印数据,看一下数据是否改变,切换到vue.js.develops插件修改数据,看一下视图是否有变化;如果没有变化,可能是vue的视图没有监听的数据的改变,数据可能不是响......
  • 巨蟒python全栈开发django3:url&&视图
    1.url正则匹配分组和命名分组2.路由分发3.url别名和反向解析4.httprequest和httpresponse的使用 内容回顾:1.jinja2(flask框架,没有内置模板对象,需要自己用jinja2)......
  • 第1章SpringMVC*概述-注册中央调度区,定义页面,修改视图解析器
    第1章SpringMVC概述1.1SpringMVC简介SpringMVC也叫Springwebmvc。是Spring框架的一部分,是在Spring3.0后发布的。1.2SpringMVC优点1.基于MVC架构......
  • Oracle 19C学习 - 21. 物化视图
    什么是物化视图Oracle物化视图是包括一个查询结果的数据库对象。它是一种非本地数据的本地化副本,或用来生成基于某种功能或者业务需求的汇总表。物化视图存储基于非本地......
  • SQL Server 查看某个表/视图 已存在的索引
    一、查看某个表/视图中存在的索引1、语法:execsp_helpindex表名/视图名2、返回代码值:0(成功)或1(失败)3、结果值:列名称 数据类型 说明index_name sysname 索引名。index_......
  • RCP如何添加透视图
    1、在plugin.xml添加透视图扩展点<extension point="org.eclipse.ui.perspectives"> <perspective class="myviewrcp2.MyPerspective" icon="icons/samples.gif"......