DRF的APIView和mixins+GenericAPIView和ListAPIView

Posted LauZyHou的短随笔

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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可以看到很多这样的写好的类,直接继承下来用很方便。

以上是关于DRF的APIView和mixins+GenericAPIView和ListAPIView的主要内容,如果未能解决你的问题,请参考以下文章

drf视图家族

77-drf视图家族及路由层补充

73-DRF的封装:APIView类及五大模块

DRF框架之视图基类APIView和GenericAPIView简介

没有模型 APIView 的 DRF 分页自定义响应

DRF ---- APIview生命周期 请求/渲染/解析/异常/响应/ 模块源码 drf配置