基于视图子类实现接口
基于视图子类实现接口
11.1 视图子类介绍
(1) CreateAPIView
提供 post 方法
继承自: GenericAPIView、CreateModelMixin
(2)ListAPIView
提供 get 方法
继承自:GenericAPIView、ListModelMixin
(3)RetireveAPIView
提供 get 方法
继承自: GenericAPIView、RetrieveModelMixin
(4)DestoryAPIView
提供 delete 方法
继承自:GenericAPIView、DestoryModelMixin
(5)UpdateAPIView
提供 put 和 patch 方法
继承自:GenericAPIView、UpdateModelMixin
(6)RetrieveUpdateAPIView
提供 get、put、patch方法
继承自: GenericAPIView、RetrieveModelMixin、UpdateModelMixin
(7)RetrieveUpdateDestoryAPIView
提供 get、put、patch、delete方法
继承自:GenericAPIView、RetrieveModelMixin、UpdateModelMixin、DestoryModelMixin
(8)RetrieveDestoryAPIView
提供 get、delete方法
继承自:GenericAPIView、RetrieveModelMixin、DestoryModelMixin
(9)ListCreateAPIView
提供 get、post方法
继承自:GenericAPIView、ListModelMixin、CreateModelMixin
11.2 快速实现接口
视图
"""
视图子类是通用视图类和模型扩展类的子类
ListAPIView = GenericAPIView + ListModelMixin 获取多条数据
CreateAPIView = GenericAPIView + CreateModelMixin 添加一条数据
RetrieveAPIView = GenericAPIView + RetrieveModelMixin 获取一条数据
UpdateAPIView = GenericAPIView + UpdateModelMixin 更新一条数据
DestroyAPIView = GenericAPIView + DestroyModelMixin 删除一条数据
组合视图子类:
ListCreateAPIView = ListAPIView + CreateAPIView
RetrieveUpdateAPIView = RetrieveAPIView + UpdateAPIView
RetrieveDestroyAPIView = RetrieveAPIView + DestroyAPIView
RetrieveUpdateDestroyAPIView = RetrieveAPIView + UpdateAPIView + DestroyAPIView
"""
from rest_framework.generics import ListAPIView, CreateAPIView, UpdateAPIView, RetrieveAPIView, DestroyAPIView,ListCreateAPIView,RetrieveUpdateDestroyAPIView
from app.models import studentsInfo
from .serializers import StudentModelSerializer
# class StudentView1(ListAPIView, CreateAPIView):
class StudentView1(ListCreateAPIView):
queryset = studentsInfo.objects.all()
serializer_class = StudentModelSerializer
# class StudentView2(UpdateAPIView, RetrieveAPIView, DestroyAPIView):
class StudentView2(RetrieveUpdateDestroyAPIView):
queryset = studentsInfo.objects.all()
serializer_class = StudentModelSerializer
路由
from django.urls import path, re_path
from . import views
urlpatterns = [
# APIView
path('students/', views.StudentView.as_view()),
re_path(r'^students/(?P<pk>\d+)/$', views.StudentAPIView.as_view()),
# GenericAPIView
path('students2/', views.StudentGenericAPIView.as_view()),
re_path(r'^students2/(?P<pk>\d+)/$', views.StudentGenericAPIView2.as_view()),
# GenericAPIView和mixin
path('students3/', views.StudentGenericAPIViewMixin.as_view()),
re_path(r'^students3/(?P<pk>\d+)/$', views.StudentGenericAPIViewMixin2.as_view()),
# 视图子类
path('students4/', views.StudentView1.as_view()),
re_path(r'^students4/(?P<pk>\d+)/$', views.StudentView2.as_view())
]