DRF的APIView和mixins+GenericAPIView和ListAPIView

APIView(继承了View)

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from .serializers import GoodsSerializer
from .models import Goods


class GoodsListView(APIView):
    def get(self, response, format=None):
        goods = Goods.objects.all()[:10]
        serializer = GoodsSerializer(goods, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        # DRf的Request中数据都已经取出放在了data属性里,使用起来很方便
        serializer = GoodsSerializer(data=request.data)
        if serializer.is_valid():
            # 这里save()根据对象是否已经存在去调用create()或者update()方法
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

 

mixins+GenericAPIView(继承了APIView)

from rest_framework import mixins
from rest_framework import generics

from .serializers import GoodsSerializer
from .models import Goods


class GoodsListView(mixins.ListModelMixin,
                    mixins.CreateModelMixin,
                    generics.GenericAPIView):
    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer

    def get(self, request, *args, **kwargs):
        # list函数在ListModelMixin里
        return self.list(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        # create函数在CreateModelMixin里
        return self.create(request, *args, **kwargs)

 

注意如果只是商品,其实不需要给post方法,因为只允许用户获取商品,而不是去提交商品(注意restful的HTTP方法的语义正确)。而管理员后台的提交商品都在admin或者xadmin里做好了。

ListAPIView的源码如下:

class ListAPIView(mixins.ListModelMixin,
                  GenericAPIView):
    """
    Concrete view for listing a queryset.
    """
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)

所以如果不要post方法,也就不要了mixins.CreateModelMixin,剩下的两个因为ListAPIView已经直接集成了,所以完全可以直接这样用:

在rest_framework模块下的generic.py里,点击左侧structure可以看到很多这样的写好的类,直接继承下来用很方便。

posted @ 2019-01-15 20:39  LauZyHou  阅读(719)  评论(0编辑  收藏  举报