ModelViewSet视图集

ModelViewSet

继承自GenericAPIVIew,同时包括了ListModelMixin、RetrieveModelMixin、CreateModelMixin、UpdateModelMixin、DestoryModelMixin。

ReadOnlyModelViewSet

继承自GenericAPIVIew,同时包括了ListModelMixin、RetrieveModelMixin。

ModelViewSet视图集python代码如下:

from rest_framework.viewsets import ModelViewSet
from book_drf.serializer import BookSerializer
from books.models import BookInfo


class Books(ModelViewSet):
    queryset = BookInfo.objects.all()  # 指定当前类视图使用的查询集数据
    serializer_class = BookSerializer  # 指定当前类视图使用的序列化器

urls配置路由python代码如下:

from . import modelviewset_view

urlpatterns = [
    url(r'^books_drf/$', modelviewset_view.Books.as_view({'get': 'list', 'post': 'create'})),
    url(r'^books_drf/(?P<pk>\d+)/$', modelviewset_view.Books.as_view({'put': 'update','get':'retrieve','delete':'destroy'})),
]