restframework-视图

三种方式

方式
mixin类编写视图
基于类的视图
ModelViewSet的视图

mixin类编写视图

Author表示例

url设计

    url(r'^authors/$', views.AuthorViewSet.as_view()),
    url(r'^authors/(?P\d+)/$', views.AuthorDetailView.as_view()),
# 不加pk会报错
# AssertionError: Expected view AuthorDetailView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.

views代码

# Author表
from rest_framework import mixins
from rest_framework import generics

class AuthorViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

class AuthorDetailView(mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        return self.update(request, *args, **kwargs)

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

基于类的视图

url设计

    url(r'^authors/$', views.AuthorViewSet.as_view()),
    url(r'^authors/(?P\d+)/$', views.AuthorDetailView.as_view()),

view代码

from rest_framework import generics

class AuthorViewSet(generics.ListCreateAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

class AuthorDetailView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

ModelViewSet的视图

url设计
五种访问方式放在同一个视图函数中,通过字典分发给不同的执行方法。

url(r'^authors/$', views.AuthorModelView.as_view({"get": "list", "post": "create"}), name="author"),
url(r'^authors/(?P\d+)/$', views.AuthorModelView.as_view({"get":"retrieve","put":"update","delete":"destroy"}),name="detailauthor")

view代码

from rest_framework import viewsets
class AuthorModelView(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorModelSerializers

你可能感兴趣的:(restframework-视图)