首页 > 技术文章 > 关于django-rest-freamwork中的View

xussi 2018-08-07 15:43 原文

view > views.APIView > generics.GenericAPIView > viewsets.GenericViewSet

1.APIView(继承 view)官方范例:

  class GoodsList(APIView): 
   """
    List all snippets, or create a new snippet.
  
""" def get(self, request, format=None):
     Goods = Snippet.objects.all()   serializer = GoodsSerializer(Goods, many=True)   return Response(serializer.data)

重写get(),指定模型,并序列化(serializer

serializer

class GoodsSerializer(serializers.Serializer):  # 类似与form的功能,但是能序列化为json
    name = serializers.CharField(required=True, max_length=100)
    click_num = serializers.IntegerField(default=0)

使用serializers.ModelSerializer:

# serializers.ModelSerializer 继承serializers.serializers(可不要指明每个字段,在fields里添加就好了)
class GoodsSerializer(serializers.ModelSerializer):  # 类似与form的功能,但是能序列化为json
    category = CategorySerializer()  # 嵌套外键,获取外键的全部信息,注意CategorySerializer已定义
    images = GoodsImageSerializer(many=True)

 

2.使用上层的generics.GenericAPIView:

在generics.GenericAPIView(view,views.APIView也是 )要重写get(),post()等方法,如果不重写表明不接受GET,POST等方法
覆盖内置变量queryset,serializer_class,get()调用了list是在mixins.ListModelMixin当中的,此函数帮助我们分页,
调用serializer完成序列化

class GoodsListView(mixins.ListModelMixin, generics.GenericAPIView):
 """ 
  商品列表页 
 """ 
    queryset = Goods.objects.all() 
    serializer_class = GoodsSerializer 
    def get(self, request, *args, **kwargs): 
        return self.list(request, *args, **kwargs)
更简单的方法:generics帮我们封装好了一些方法可以直接用:


可以直接使用ListAPIView,因为已经帮我们填入了mixins.ListModelMixin和GenericAPIView
class ListAPIView(mixins.ListModelMixin,
                  GenericAPIView):
    """
    Concrete view for listing a queryset.
    """
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

上边的代码改为:

class GoodsListView(generics.ListAPIView):
 """ 
  商品列表页 
 """ 
    queryset = Goods.objects.all() 
    serializer_class = GoodsSerializer 

分页设置:在setting中设置:

 REST_FRAMEWORK = {   # rest-framework的配置
'PAGE_SIZE': 10, # 分页配置
}

自定义分页配置:

class GoodsPagination(PageNumberPagination):  # 定制分页设置
page_size = 12
page_size_query_param = 'page_size'
page_query_param = "page"
max_page_size = 100

 字段引用:

pagination_class = GoodsPagination


更更好用的ViewSet:
class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data)


作者:天涯明月笙
链接:https://www.jianshu.com/p/6a6fa62d8152
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data)


作者:天涯明月笙
链接:https://www.jianshu.com/p/6a6fa62d8152
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data)


作者:天涯明月笙
链接:https://www.jianshu.com/p/6a6fa62d8152
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

继承了ViewSetMixin, generics.GenericAPIView,也就是加了ViewSetMixin中的方法
class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
    """
    The GenericViewSet class does not provide any actions by default,
    but does include the base set of generic view behavior, such as
    the `get_object` and `get_queryset` methods.
    """
    pass

ViewSetMixin部分代码
class ViewSetMixin(object):
    @classonlymethod
    def as_view(cls, actions=None, **initkwargs):

重写as_view使得注册URL变得更简单!

使用router:

from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'goods', GoodsListViewSet, base_name="goods")
urlpatterns = [
url(r'^', include(router.urls)),
]

router自动把GET,POST等绑定

自定义绑定:

goods_list = GoodsListViewSet.as_view({
'get': 'list',
})
url(r'goods/$', goods_list, name='goods-list'),

4.queryset为得到所有的模型,要是想要筛选则要使用:
def get_queryset(self):
  return Goods.object.filter(shop_price__get=100) 返回大于100的商品
那么queryset = Goods.objects.all()就不需要了

5,minxin:

 

 
 

推荐阅读