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)),    (等同于方式一的写法)
    ]
  • 相关阅读:
    【数据结构与算法】用go语言实现数组结构及其操作
    ElasticSearch搜索引擎
    【系统】Libevent库和Libev
    pod管理调度约束、与健康状态检查
    使用yaml配置文件管理资源
    Oracle中exists替代in语句
    【oracle】通过存储过程名查看package名
    解决Flink消费Kafka信息,结果存储在Mysql的重复消费问题
    利用Flink消费Kafka数据保证全局有序
    Oracle 字符集的查看和修改
  • 原文地址:https://www.cnblogs.com/sunch/p/9993633.html
Copyright © 2011-2022 走看看