当前位置:网站首页>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 ):
边栏推荐
- busybox login: can't execute '/bin/bash': No such file or directory 解决方法
- Install MySQL using CentOS yum
- MapReduce instance (III): data De duplication
- Pychart import existing project
- 时间序列——使用tsfresh进行分类任务
- Pycharm导入已有的Project
- : 0xc0000005: an access conflict occurs when writing position 0x01458000 - to be solved
- 第一章 马克思主义哲学是科学的世界观和方法论
- 4-digit random data
- 编码技巧——全局日志开关
猜你喜欢

MySQL index

: 0xc0000005: an access conflict occurs when writing position 0x01458000 - to be solved

JSP Foundation

Coding skills - Global exception capture & unified return body & Business exception

时间序列——使用tsfresh进行分类任务

flume增量采集mysql数据到kafka

单机高并发模型设计

webRTC中的coturn服务安装

Mapreduce实例(一):WordCount

Understand │ what is cross domain? How to solve cross domain problems?
随机推荐
编码技巧——全局日志开关
ARIMA model selection and residuals
Delete node quickly and efficiently_ modules
Common Oracle statements
Text capture picture (Wallpaper of Nezha's demon child coming to the world)
Excel提取重复项
Openwrt adds RTC (mcp7940 I2C bus) drive details
Axure 安装图标字体元件库
Coturn service installation in webrtc
云管平台中租户以及多租户概念简单说明
centos yum方式安装mysql
Paper_ Book
Six capabilities of test and development
少见的按位操作符
测试新手学习宝典(有思路有想法)
For enterprise operation and maintenance security, use the cloud housekeeper fortress machine!
It can carry 100 people! Musk releases the strongest "starship" in history! Go to Mars as early as next year!
Solve mt7620 continuous cycle uboot (LZMA error 1 - must reset board to recover)
Clickhouse 20.x distributed table testing and chproxy deployment (II)
Characters generated by JMeter function assistant in jmeter5.3 and later versions cannot be copied when they are grayed out