Serializer的基本封装(视图集、路由器)

修改继承类

from rest_framework import viewsets

class PublisherViewSet(viewset.ModelViewSet):
    queryset = Publisher.objects.all()
    serializer_class = PublisherSerializer

class BookViewSet(viewsets.ModelviewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializers


视图集

配置视图集路由
# urls.py
book_list = views.BookViewSet.as_view(
    {  # 自定义可使用请求方法
        'get':'list',
        'post':'create'
    }
)
publisher_list = views.PublisherViewSet.as_view(
    {
        'get':'list',
        'post':'create'
    }
)
book_detail = views.BookViewSet.as_view(
    {
        'get':'retrieve',
        'put':'update',
        'patch':'partial_update',
        'delete':'destory'
    }
)
publisher_detail = views.PublisherViewSet.as_view(
    {
        'get':'retrieve',
        'put':'update',
        'patch':'partial_update',
        'delete':'destory'
    }
)
urlpattern = [  # 注意书写格式 (清晰、整洁)
    url(r'books/$',book_list, name='book-list'),
    url(r'books/(?P\d+)$',book_list, name='book-detail'),
    url(r'publishers/$',publisher_list, name='publisher-list'),
    url(r'publishers/(?P\d+)$',publisher_list, name='publisher-detail')
]


路由器

# urls.py
from rest_framework.router import DefaultRouter
# 将我们的视图集注册到路由器当中
router = DefaultRouter()
# 若存在超链接,需同时注册
router.register(r'books', views.BookViewSet)
router.register(r'publishers',views.PublisherViewSet)

urlpattern = [
    url(r'^', include(router.urls))
]

你可能感兴趣的:(Serializer的基本封装(视图集、路由器))