drf 高级六 视图

时间:2023-02-25 22:59:45

每个视图几乎都是相互继承,增加某些实用功能

基础视图

最基础的两个视图。

# APIView
from django.views.generic import View
class APIView(View):
    pass

# GenericAPIView
from rest_framework import mixins, views
class GenericAPIView(views.APIView):
    pass

准确的说APIView是最基础的视图。所有视图都是基于它增加了变化。而这些变化来自于类属性。GenericAPIView重要功能是来自类属性QuerySet的分页。这位下面增加一些Minin类增加了前提,也就是,你只需要关注querysetserializer就能完成数据的增删改查,也就是drf最大有点—快速构建一些接口。下面是一些通过Mixin扩展的一些视图,即使他们不是最终形态

扩展视图

class CreateAPIView(mixins.CreateModelMixin,
                    GenericAPIView):
    """
    Concrete view for creating a model instance.
    """
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
# ListAPIView
class RetrieveAPIView(mixins.RetrieveModelMixin, GenericAPIView):
    pass
# DestroyAPIView
class DestroyAPIView(mixins.DestroyModelMixin,
                     GenericAPIView):
    pass
# UpdateAPIView
class UpdateAPIView(mixins.UpdateModelMixin,
                    GenericAPIView):
    pass
# ListCreateAPIView
class ListCreateAPIView(mixins.ListModelMixin,
                        mixins.CreateModelMixin,
                        GenericAPIView):
    pass
# RetrieveUpdateAPIView
class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
                            mixins.UpdateModelMixin,
                            GenericAPIView):
    pass
# RetrieveDestroyAPIView
class RetrieveDestroyAPIView(mixins.RetrieveModelMixin,
                             mixins.DestroyModelMixin,
                             GenericAPIView):
    pass
 
# RetrieveUpdateDestroyAPIView
class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
                                   mixins.UpdateModelMixin,
                                   mixins.DestroyModelMixin,
                                   GenericAPIView):
    pass

CreateAPIView继承了CreateModelMixin它提供了通过serializerqueryset就能完成对数据的增加操作。serializer对数据进行验证保存。下面是CreateModelMixin的源码。

class CreateModelMixin:
    """
    Create a model instance.
    """
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=False)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        serializer.save()

    def get_success_headers(self, data):
        try:
            return {'Location': str(data[api_settings.URL_FIELD_NAME])}
        except (TypeError, KeyError):
            return {}

路由映射到CreateAPIViewpost方法中最终调用mixincreate方法。首先获取一个数据验证过的serializer,如果抛出异常将被drf异常捕获。如果没有异常调用序列化器的save方法保存数据。其他类似的函数也是同样的逻辑。此方法仅仅将添加mixin集成到一个视图中。更加让我们减少代码量的是视图集也许你只需要三行代码就能完成一个增删改查操作。

注意:这里还不能将所有继承在一起,由于drf的理念是在查单个、删除、更新放到了url中实现那么,它将和操作多个数据产生冲突。它还需要一个工具将一个和多个操作融合的方法—视图集