Django-RESTful Api之ViewSets和Routers

目的

  • **目的:**介绍另一种基于类的视图的写法,它的抽象程度更高,代码量更少

使用ViewSets重构视图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from myApp.models import Student, Grade
from django.contrib.auth.models import User
from myApp.serializers import StudentSerializer, UserSerializer
from rest_framework import generics
from myApp.permissions import IsOwnerOrReadOnly
from rest_framework import permissions
from rest_framework import viewsets

'''
get /students
post /students
get /students/pk
put /students/pk
delete / students/pk
'''


class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)

def perform_create(self, serializer):
serializer.save(owner=self.request.user)
1
2
3
class UserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer

重构路由

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from django.conf.urls import url, include
from myApp.views import StudentViewSet, UserViewSet
from rest_framework.urlpatterns import format_suffix_patterns

student_list = StudentViewSet.as_view({
'get': 'list',
'post': 'create',
})
student_detail = StudentViewSet.as_view({
'get': 'retrieve',
'put': 'update',
'patch': 'partial_update',
'delete': 'destroy',
})

user_list = UserViewSet.as_view({
'get': 'list',
})
user_detail = UserViewSet.as_view({
'get': 'retrieve',
})

urlpatterns = format_suffix_patterns([
url(r'^students/$', student_list, name='studentList'),
url(r'^students/(?P<pk>\d+)', student_detail, name='studentDetail'),
url(r'^users/$', user_list, name='userList'),
url(r'^users/(?P<pk>\d+)', user_detail, name='userDetail'),
])

使用Routers

1
2
3
4
5
6
7
8
9
10
11
from django.conf.urls import url, include
from myApp import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'students', views.StudentViewSet)
router.register(r'users', views.UserViewSet)

urlpatterns = [
url(r'^', include(router.urls))
]
本文结束 感谢您的阅读
正在加载今日诗词....