• drf-视图家族练习


    视图类

    from rest_framework.viewsets import ViewSetMixin, GenericViewSet, ViewSet, ModelViewSet
    from .response import APIResponse
    from rest_framework.response import Response
    
    
    class Car(ModelViewSet):
        queryset = models.Car.objects.filter(is_delete=False).all()
        serializer_class = serializers.CarModelSerializer
    
        # 群查
        def list(self, request, *args, **kwargs):
            response = super().list(request, *args, **kwargs)
            return APIResponse(status=response.data)
    
        # 单查
        def retrieve(self, request, *args, **kwargs):
            response = super().retrieve(request, *args, **kwargs)
            return APIResponse(status=response.data)
    
        # 局部单改
        def partial_update(self, request, *args, **kwargs):
            response = super().partial_update(request, *args, **kwargs)
            return APIResponse(status=response.data)
    
        # 群改
        def many_partial_update(self, request, *args, **kwargs):
            request_data = request.data
            try:
                pks = []
                for dic in request_data:
                    pk = dic.pop('id')
                    pks.append(pk)
                car_query = models.Car.objects.filter(is_delete=False, pk__in=pks).all()
                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(results=self.get_serializer(car_list, many=True).data)
    
        # 整体单改
        def update(self, request, *args, **kwargs):
            response = super().update(request, *args, **kwargs)
            return APIResponse(status=response.data)
    
        # 单删
        def destroy(self, request, *args, **kwargs):
            car_obj = self.get_object()
            car_obj.is_delete = True
            car_obj.save()
            return APIResponse(msg='删除成功')
    
        # 群增
        def create(self, request, *args, **kwargs):
            request_data = request.data
            if isinstance(request_data, list):
                # 内部方法直接将data和many值传进去就可以传到序列化了
                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)
    
    
    

    序列化类

    from rest_framework import serializers
    from . import models
    # 汽车表序列化
    class CarModelSerializer(serializers.ModelSerializer):
        class Meta:
            # list_serializer_class固定写法,内部方法
            list_serializer_class = CarListSerializer
            model = models.Car
            fields = ['name', 'color', 'price', 'img', 'color_car', 'store', 'sponsor', 'store_info',
                      'sponsor_list']
    
            extra_kwargs = {
                'color': {
                    'write_only': True
                },
                'sponsor': {
                    'write_only': True
                },
                'store':{
                    'write_only': True
                }
            }
    
    
  • 相关阅读:
    Navicat Premium 12连接Oracle时提示oracle library is not loaded的问题解决
    事务传播机制Propagation.REQUIRES_NEW
    @ApiImplicitParams、ApiImplicitParam的使用
    启动微服务项目的时候报redisInit错误---本地启动redis服务
    Swagger介绍及使用
    mybaitis框架-trim标签
    pgadmin怎样创建新的连接
    微服务项目启动
    管理中第一可怕之事(2) . 分类: 项目管理 2014-06-25 18:54 257人阅读 评论(0) 收藏
    管理中第一可怕之事(1) . 分类: 项目管理 2014-06-25 18:53 264人阅读 评论(0) 收藏
  • 原文地址:https://www.cnblogs.com/mqhpy/p/12126556.html
Copyright © 2020-2023  润新知