zoukankan      html  css  js  c++  java
  • restframework视图三部曲

    mixins的玩法

    from rest_framework import mixins
    from rest_framework import generics
    
    class AuthorView(mixins.CreateModelMixin, mixins.ListModelMixin, generics.GenericAPIView):
        # 初始化两个变量
        queryset = Author.objects.all()
        serializer_class = AuthorModelSerializer
    
        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.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
        # 初始化两个变量
        queryset = Author.objects.all()
        serializer_class = AuthorModelSerializer
    
        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(request, *args, **kwargs):
            return self.destroy(request, *args, **kwargs)

    generic的玩法

    from rest_framework import mixins
    from rest_framework import generics
    
    
    class AuthorView(generics.ListCreateAPIView):
        queryset = Author.objects.all()
        serializer_class = AuthorModelSerializer
    
    
    class AuthorDetailView(generics.RetrieveUpdateDestroyAPIView):
        queryset = Author.objects.all()
        serializer_class = AuthorModelSerializer

    终极玩法

    views.py

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

    urls.py

    # 方式一,自己手写
    urlpatterns = [
        url(r'^authors/$', views.AuthorViewSet.as_view({"get": "list", "post": "create"}), name="author_list"),
        url(r'^authors/(?P<pk>d+)/$', views.AuthorViewSet.as_view({"get": "retrieve", "put": "update", "delete": "destroy"}), name="author_detail"),
    ]
    
    
    # 方式二,针对上面的两条url的分发
    from rest_framework import routers
    routers = routers.DefaultRouter()
    routers.register("authors", views.AuthorViewSet)    # authors是url前缀
    urlpatterns = [
        url(r'', include(routers.urls)),    (等同于方式一的写法)
    ]
  • 相关阅读:
    Collectors.reducing总结
    Ubuntu 换源看这一篇就够了
    基于Vue2和Node.js的反欺诈系统设计与实现
    Flink源码解析(四)——从Flink集群部署和任务提交模式看Flink任务的核心组件
    SaaS架构(二) 多租户数据隔离方案
    网络IO模型(BIO,NIO,AIO)
    Gale-Shapley算法
    Java 内存模型
    上位机那些事儿
    三菱PLC之SLMP协议报文说明
  • 原文地址:https://www.cnblogs.com/sunch/p/9993633.html
Copyright © 2011-2022 走看看