当前位置:网站首页>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 ):
边栏推荐
- 借5G东风,联发科欲再战高端市场?
- Constraints, design and joint query of data table -- 8000 word strategy + Exercise answers
- 逗号操作符你有用过吗?
- It can carry 100 people! Musk releases the strongest "starship" in history! Go to Mars as early as next year!
- scrapy爬虫框架
- Web test learning notes 01
- Vant UI toast and dialog use
- profileapi. h header
- QT (VI) value and string conversion
- 单机高并发模型设计
猜你喜欢

测试新手学习宝典(有思路有想法)

mysql设置密码时报错 Your password does not satisfy the current policy requirements(修改·mysql密码策略设置简单密码)

DEX and AMMS of DFI security

2.2 basic elements of JMeter

Nacos

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

Openwrt adds RTC (mcp7940 I2C bus) drive details

Pychart import existing project

Penetration test - dry goods | 80 + network security interview experience post (interview)

SQL multi table query
随机推荐
DeFi安全之DEX与AMMs
openwrt 编译驱动模块(在openwrt源代码外部任意位置编写代码,独立模块化编译.ko)
firefox旧版本
JWT简介
百度图片复制图片地址
DRF学习笔记(四):DRF视图
Short video mall system, system prompt box, confirmation box, click blank to close the pop-up box
台积电的反击:指控格芯侵犯25项专利,并要求禁售!
Ncnn reasoning framework installation; Onnx to ncnn
Openwrt adds RTC (mcp7940 I2C bus) drive details
借5G东风,联发科欲再战高端市场?
For enterprise operation and maintenance security, use the cloud housekeeper fortress machine!
busybox login: can't execute '/bin/bash': No such file or directory 解决方法
判断数据的精确类型
ARIMA模型选择与残差
Paper_ Book
Single machine high concurrency model design
ARIMA model selection and residuals
时间序列-ARIMA模型
: 0xc0000005: an access conflict occurs when writing position 0x01458000 - to be solved