当前位置:网站首页>DRF learning notes (V): viewset
DRF learning notes (V): viewset
2022-07-27 16:19:00 【fresh_ nam】
List of articles
Preface
Using view sets ViewSet, You can put a series of logically related actions into a class :
- list() Provide a set of data
- retrieve() Provide single data
- create() Create data
- update() Update saved data
- destory() Delete data
ViewSet The view set class is no longer implemented get()、post() Other methods , It's about acting action Such as list() 、create() etc. .
View sets are only used as_view() Method time , Will be action The action corresponds to the specific request mode . Such as :
from rest_framework.response import Response
from demo.models import ClassInfo
from demo.serializers import ClassInfoSerializer
from rest_framework import viewsets, status
class ClassViewSet(viewsets.ViewSet):
# Get all class data
def list(self, request):
Classes = ClassInfo.objects.all()
serializer = ClassInfoSerializer(Classes, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
try:
Class = ClassInfo.objects.get(id=pk)
except ClassInfo.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = ClassInfoSerializer(Class)
return Response(serializer.data)
Setting the route is , We can do the following
demo/uels.py
from django.urls import path
from demo import views
urlpatterns = [
······
path('classes/', views.ClassViewSet.as_view({
'get': 'list'})),
path('classes/<int:pk>/', views.ClassViewSet.as_view({
'get': 'retrieve'})),
]
result :

One 、 Common view set parent class
1) ViewSet
Inherited from APIView And ViewSetMixin, It also works with APIView similar , Provides authentication 、 Permission to check 、 Traffic management, etc .
ViewSet Mainly through inheritance ViewSetMixin To implement calling as_view() When you enter the dictionary ( Such as {‘get’:‘list’}) The mapping processing work of .
stay ViewSet in , No action provided action Method , We need to do it ourselves action Method .
2)GenericViewSet
Use ViewSet It's usually not convenient , because list、retrieve、create、update、destory We need to write our own methods , And these methods are different from the ones mentioned above Mixin The method provided by the extension class has the same name , So we can inherit Mixin Extend classes to reuse these methods without having to write your own . however Mixin Extension classes depend on GenericAPIView, So we need to inherit GenericAPIView.
GenericViewSet It helps us to finish this kind of inheritance work , Inherited from GenericAPIView And ViewSetMixin, In the implementation of the call as_view() When you enter the dictionary ( Such as {‘get’:‘list’}) At the same time that the mapping process works , It also provides GenericAPIView Basic methods provided , It can be directly matched with Mixin Extension classes use .
give an example :
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
class ClassInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
url The definition of
demo/urls.py
urlpatterns = [
······
path('classes_set/', views.ClassInfoViewSet.as_view({
'get': 'list'})),
path('classes_set/<int:pk>/', views.ClassInfoViewSet.as_view({
'get': 'retrieve'})),
]
The result is the same as above :

Two 、 Define additional views in the view set action action
In the view set , In addition to the above default method actions , You can also add custom actions .
To add a custom action, you need to use rest_framework.decorators.action Decorator .
With action The method name of decorator decoration will be used as action Action name , And list、retrieve equivalent .
action The decorator can receive two parameters :
- methods: The action Supported request mode , List delivery
- detail: Said is action Whether the object to be processed in is the object of view resource ( That is, whether to pass url Path to get the primary key )
(1)True Means to use URL The data object corresponding to the obtained primary key
(2)False No use URL Get primary key
give an example :
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from rest_framework.decorators import action
class ClassInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
queryset = ClassInfo.objects.all()
serializer_class = ClassInfoSerializer
# detail by False Indicates that there is no need to deal with specific BookInfo object
@action(methods=['get'], detail=False)
def latest(self, request):
""" return id The last class """
Class = ClassInfo.objects.latest('id')
serializer = ClassInfoSerializer(Class)
return Response(serializer.data)
# detail by True, Means to deal with specific and pk The primary key corresponds to BookInfo object
@action(methods=['put'], detail=True)
def updata(self, request, pk):
""" Modify class information """
Class = self.get_object()
Class.number = request.data.get('number')
Class.grade = request.data.get('grade')
Class.save()
serializer = self.get_serializer(Class)
return Response(serializer.data)
url The definition of
demo/urls.py
from django.contrib import admin
from django.urls import path, include
from demo import views
urlpatterns = [
······
path('classes_set/<int:pk>/', views.ClassInfoViewSet.as_view({
'get': 'retrieve', 'put': 'updata'})),
path('classes_set_latest/', views.ClassInfoViewSet.as_view({
'get': 'latest'})),
]
result :

end
drf The basic content of is finished , If you don't understand, you can leave a message in the comment area .
Add
Sometimes we customize too many actions , It is inconvenient to add paths , therefore drf It provides us with the routing function , Automatically generate paths for view sets .
Use : Annotate the original route , Add the following code
from django.contrib import admin
from django.urls import path, include, re_path
from demo import views
from rest_framework.routers import DefaultRouter
# urlpatterns = [
# path('classes_set/<int:pk>/', views.ClassInfoViewSet.as_view({'get': 'retrieve', 'put': 'updata'})),
# path('classes_set_latest/', views.ClassInfoViewSet.as_view({'get': 'latest'})),
# ]
# Define total path
urlpatterns = []
# Define routes
classes_router = DefaultRouter()
# Registered routing
classes_router.register("classes_set", views.ClassInfoViewSet, basename="classes_set")
# Add the path of the registered route to the total path
urlpatterns += classes_router.urls
among ,register The parameter is register( Route prefix , View set ,basename)
The access path becomes : ( Prefix )/ Route prefix / Function name
The result remains unchanged. ( Notice that the path has changed ):
边栏推荐
- Live broadcast software development, customized pop-up effect of tools
- flink打包程序提交任务示例
- 4位数的随机数据
- Constraints, design and joint query of data table -- 8000 word strategy + Exercise answers
- 微信小程序个人号开通流量主
- TSMC's counterattack: it accused lattice core of infringing 25 patents and asked for prohibition!
- DRF学习笔记(四):DRF视图
- Samsung closes its last mobile phone factory in China
- Reduce program ROM ram, GCC -ffunction sections -fdata sections -wl, – detailed explanation of GC sections parameters
- Scratch crawler framework
猜你喜欢

QT (VI) value and string conversion

时间序列-ARIMA模型

MapReduce instance (II): Average

MySQL index

Mlx90640 infrared thermal imager temperature sensor module development notes (VII)

web测试学习笔记01

SQL multi table query

First acquaintance with MySQL database

Excel extract duplicates

Common tool classes under JUC package
随机推荐
JMeter5.3 及以后的版本jmeter函数助手生成的字符在置灰无法复制
JWT简介
时间序列-ARIMA模型
Understand │ what is cross domain? How to solve cross domain problems?
编码技巧——全局异常捕获&统一的返回体&业务异常
判断数据的精确类型
juc包下常用工具类
TSMC's counterattack: it accused lattice core of infringing 25 patents and asked for prohibition!
可载100人!马斯克发布史上最强“星际飞船” !最早明年上火星!
Test novice learning classic (with ideas)
43亿欧元现金收购欧司朗宣告失败!ams表示将继续收购
台积电6纳米制程将于明年一季度进入试产
JSP基础
Solve mt7620 continuous cycle uboot (LZMA error 1 - must reset board to recover)
Sword finger offer 51. reverse pairs in the array
快速高效删除node_modules
Coding technique - Global log switch
Join hands with sifive, Galanz will enter the semiconductor field! Exposure of two self-developed chips
Web test learning notes 01
Pycharm导入已有的本地安装包