码迷,mamicode.com
首页 > 其他好文 > 详细

12.30 视图集

时间:2019-12-30 23:05:43      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:自己   直接   python   upd   view设置   pre   require   response   映射关系   

视图家族

from rest_framework import views, mixins, generics, viewsets

views:视图类 - APIView,GenericAPIView(generics中)
mixins:视图工具类 - CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
generics:工具视图类 - 九个类
viewsets:视图集 - 两个视图集基类,两个视图集子类,一个工具类

两个视图基类:APIView和GenericAPIView

  • APIView是rest_framework提供的所有视图的基类,继承自django的view父类
  • 拥有View的所有 重写as_view 重写dispatch 一系列的类属性
class CarAPIView(APIView):
    # 群查
    def get(self, request, *args, **kwargs):
        car_query = models.Car.objects.filter(is_delete=False).all()
        car_ser = serializers.CarModelSerializer(instance=car_query, many=True)
        return APIResponse(results=car_ser.data)
  • GenericAPIView继承APIView,所以拥有APIView的所有。提供as_view()等,获取当前视图类中queryset和serializer_class ,为mixins扩展类的执行提供支持
  • 视图类必须提供一个queryset,用于后续的操作
from rest_framework.generics import GenericAPIView
class CarGenericAPIView(GenericAPIView):
    # 不能直接写到objects结束,因为objects结束时,不是QuerySet对象,而是Manager对象,但 .all() 和 .filter() 后一定是QuerySet对象
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer
    lookup_url_kwarg = 'pk'  #提供的获取主键的变量和源码一样,就可以省略不写
  • 封装了获取对象和序列化的方法
# 单查
    def get(self, request, *args, **kwargs):
        # pk = kwargs.get('pk')
        # car_obj = models.Car.objects.filter(is_delete=False).filter(pk=pk).first()
        car_obj = self.get_object()  #返回所需的模型类数据对象

        # car_ser = serializers.CarModelSerializer(car_obj)
        car_ser = self.get_serializer(car_obj)  #返回序列化器对象

        return APIResponse(results=car_ser.data)

视图工具类:mixins

  • RetrieveModelMixin 详情视图扩展类,提供def retrieve(self, request, *args, **kwargs):方法,可以快速返回一个存在的数据对象
  • ListModelMixin:列表视图扩展类,提供def list(self, request, *args, **kwargs):方法,该list方法可以对数据过滤和分页
  • CreateModelMixin:创建视图扩展类,提供def create(self, request, *args, **kwargs):方法快速实现创建资源的视图
  • UpdateModelMixin:更新视图扩展类,提供update方法和partial_update方法,更新存在的对象
  • DestroyModelMixin:删除视图扩展类,提供destroy方法,删除存在的对象
  • 六个方法的实现体,调用的方法就是GenericAPIView提供的,所以要配合GenericAPIView类使用
from rest_framework.mixins import RetrieveModelMixin, ListModelMixin, CreateModelMixin
class CarReadCreateGenericAPIView(ListModelMixin, RetrieveModelMixin, CreateModelMixin, GenericAPIView):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer
    lookup_url_kwarg = 'pk'
    # 群查
    # """
    def get(self, request, *args, **kwargs):
        # car_query = self.get_queryset()
        # car_ser = self.get_serializer(car_query, many=True)
        # return APIResponse(results=car_ser.data)
        return self.list(request, *args, **kwargs)
    # 单增
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)
  • Generics工具视图类(七个功能视图子类)

    • class RetrieveAPIView(mixins.RetrieveModelMixin,
                            GenericAPIView)
         提供get方法 
    • class ListAPIView(mixins.ListModelMixin,
                        GenericAPIView): 
         提供get方法
    • class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
                                         mixins.UpdateModelMixin,
                                        mixins.DestroyModelMixin,
                                         GenericAPIView):
         提供get、put、patch、delete方法
  • queryset 指明使用的数据查询集
  • serializer_class 指明视图使用的序列化器

# 单独完成单查接口
from rest_framework.generics import RetrieveAPIView
class CarRetrieveAPIView(RetrieveAPIView):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer
    lookup_url_kwarg = 'pk'

# 单独完成群查接口
from rest_framework.generics import ListAPIView
class CarListAPIView(ListAPIView):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer


# 单查(get)、单整体改(put)、单局部改(patch)、单删接口(delete)
from rest_framework.generics import RetrieveUpdateDestroyAPIView
class CarRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer

视图集-ViewSet

  • 视图集都继承了ViewSetMixin类,该类重写了as_view方法,相比APIView的as_view方法,额外多了参数actions
  • as_view({‘get‘: ‘list‘}) 传入的{‘get‘: ‘list‘}就被actions接收,原理是将get请求映射给视图类的list函数进行处理
  • GenericViewSet 继承自ViewSetMixin, GenericAPIView,除了传入字典的提供映射工作,还提供了GenericAPIView的基础方法,可以直接搭配Mixin扩展类使用
  • ReadOnlyModelViewSet,ModelViewSet两个视图集子类继承自GenericViewSet,就是做了一堆mixin与GenericViewSet相结合,自己在urls文件中配置as_view设置映射关系
url(r'^v7/cars/$', views.CarModelViewSet.as_view({
        'get': 'list',
        'post': 'create',
        'put': 'many_update',
        'patch': 'many_partial_update',
        'delete': 'many_destroy',
    })),
    url(r'^v7/cars/(?P<pk>\d+)/$', views.CarModelViewSet.as_view({
        'get': 'retrieve',
        'put': 'update',
        'patch': 'partial_update',
        'delete': 'destroy',
    })),
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('v7/cars', views.CarModelViewSet, basename='car')
# router.register('books', views.BookModelViewSet, basename='book')
# router.register('users', views.UserModelViewSet, basename='user')
urlpatterns = [url(r'', include(router.urls))]
print(router.urls)
# 六大接口
class CarModelViewSet(ModelViewSet):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer
    
    # 分析:从实际开发角度分析不合理点
    # 1)没有群增,群整体改,群局部改,群删四个接口
    # 2)删除操作视图集默认走的destroy方法是将资源从数据库中删除,通常对is_delete字段修改表示删除
    # 3)响应的结果只有数据,没有数据状态码和状态信息

     # 解决1,
    # 群整体改,群局部改,全删三个接口可以独立成三个方法
    def many_update(self, request, *args, **kwargs):
        request_data = request.data
        try:
            pks = []
            for dic in request_data:
                pk = dic.pop('pk')
                pks.append(pk)
            car_query = self.get_queryset()
            if len(pks) != len(car_query):
                raise Exception('pk对应的数据不存在')
        except Exception as e:
            return Response({'detail': '%s' % e}, status=400)
        car_ser = self.get_serializer(instance=car_query, data=request_data, many=True)
        car_ser.is_valid(raise_exception=True)
        car_list = car_ser.save()
        return APIResponse(msg='群整体改成功', results=self.get_serializer(car_list, many=True).data)

    def many_partial_update(self, request, *args, **kwargs):
        request_data = request.data
        try:
            pks = []
            for dic in request_data:
                pk = dic.pop('pk')
                pks.append(pk)
            car_query = self.get_queryset()
            if len(pks) != len(car_query):
                raise Exception('pk对应的数据不存在')
        except Exception as e:
            return Response({'detail': '%s' % e}, status=400)
        car_ser = self.get_serializer(instance=car_query, data=request_data, many=True, partial=True)
        car_ser.is_valid(raise_exception=True)
        car_list = car_ser.save()
        return APIResponse(msg='群局部改成功', results=self.get_serializer(car_list, many=True).data)

    def many_destroy(self, request, *args, **kwargs):
        try:
            rows=self.get_queryset().update(is_delete=True)
        except:
            return APIResponse(1, '数据有误')
        if rows:
            return APIResponse(0, '群删成功')
        return APIResponse(1, '删除失败')

    # 群增与单增必须公用一个接口,都要走create方法 - 重写create方法,用逻辑进行拆分
    def create(self, request, *args, **kwargs):
        request_data = request.data
        if isinstance(request_data, list):
            car_ser = self.get_serializer(data=request_data, many=True)
            car_ser.is_valid(raise_exception=True)
            car_obj = car_ser.save()
            return APIResponse(msg='群增成功', results=self.get_serializer(car_obj, many=True).data)

        return super().create(request, *args, **kwargs)

    # 解决2,destroy方法是完成is_delete字段值修改 - 重写destroy方法,自定义实现体
    def destroy(self, request, *args, **kwargs):
        car_obj = self.get_object()
        car_obj.is_delete = True
        car_obj.save()
        return APIResponse(msg='删除成功')

    # 解决3,让群查有状态码和状态信息 - 重写list方法
    def list(self, request, *args, **kwargs):
        response = super().list(request, *args, **kwargs)
        return APIResponse(results=response.data)
  • 用子序列化完成外键,外键就不能参与反序列化,传过来的数据还要进入子序列化类,处理起来牵连众多。处理时原先的外键只参与反序列化,自定义的序列化字段参与序列化展示给前端。
from rest_framework import serializers
from . import models

class SponsorModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Sponsor
        fields = ('name', 'phone')

class CarModelSerializer(serializers.ModelSerializer):
    # sponsors = SponsorModelSerializer(many=True)  #这里不能用子序列化
    class Meta:
        model = models.Car
        fields = ('name', 'price', 'brand_name', 'sponsor_list', 'brand', 'sponsors')
        extra_kwargs = {
            'brand': {
                'required': True,
                'write_only': True
            },
            'sponsors': {
                'required': True,
                'write_only': True
            },
        }

12.30 视图集

标签:自己   直接   python   upd   view设置   pre   require   response   映射关系   

原文地址:https://www.cnblogs.com/lidandanaa/p/12121973.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!