视图集
前面用的是类视图,一个表的增删改查会写成不通过类视图,还以之前的例子来演示下视图集的用法。
导入 viewsets
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework import permissions
from rest_framework import viewsets
from project2s.permissions import IsStudentOrReadonly
from project2s.models import Student
from project2s.serializers import ProjectSerializers,UserSerializers
# 视图集
# 继承viewsets.ModelViewSet
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = ProjectSerializers
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsStudentOrReadonly] # 添加权限未登录时校验权限
def perform_create(self, serializer):
serializer.save(name=self.request.user)
# 继承viewsets.ReadOnlyModelViewSet
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializers
viewsets.ModelViewSet源码继承了如下类:
viewsets.ReadOnlyModelViewSet 源码继承了如下类:
路由器配置
导入DefaultRouter 类
from rest_framework.routers import DefaultRouter
通过register注册路由,其会通过请求方法自动解析成路由
from django.urls import path, include
from project2s import views
from rest_framework.routers import DefaultRouter
# 通过请求方法对应到继承的视图的方法
student_list = views.StudentViewSet.as_view({'get': 'list', 'post': 'create'})
student_detail = views.StudentViewSet.as_view(
{'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})
router = DefaultRouter()
router.register('students', views.StudentViewSet) # 注册路由
router.register('user', views.UserViewSet) # 注册路由
urlpatterns = [
path('', include(router.urls)),
path('', include(router.urls)),
]
结果: