一、概要schema
二、概念concept
APIView:继承并扩充了django的view
ViewSetMixin:重写了as_view方法,提供了http动词到视图中具体方法的绑定,比如get映射到list方法
GenericAPIViewSet:通用API view
ListAPIView:具体的API view
ListModelMixin:提供了list方法,省去了用户自己实现list方法的麻烦,只需要在urls里as_view一下
xxxView:用户自定义的view,比如GoodsListView,混合了ListAPIView和若干model mixins
xxxViewSet:用户自定义的viewset,比如GoodslistViewSet
三、示例example
class ListUsers(APIView):
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (p ermissions.IsAdminUser,)
def get(self, request, format=None):
usernames = [user.username for user in User.objects.all()]
return Response(usernames)
class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_fields = ('account', 'username')
class CreateListRetrieveViewSet(mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
viewsets.GenericViewSet):
"""
A viewset that provides `retrieve`, `create`, and `list` actions.
To use it, override the class and set the `.queryset` and
`.serializer_class` attributes.
"""
pass
from myapp.views import UserViewSet
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'users', UserViewSet, base_name='user')
urlpatterns = router.urls