12.30作业

查看并研究ListAPIView工具视图类,继承该类完成汽车资源的群查接口,汽车资源需要有image资源,查看接口image资源的值

from rest_framework.generics import ListAPIView
class CarListAPIView(ListAPIView):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializers.CarModelSerializer

研究GenericViewSet工具集,继承该类完成汽车资源的单查,群查,单增,单改,单删接口

from rest_framework.viewsets import GenericViewSet

class ViewGenericViewSet(GenericViewSet):
    queryset = models.Car.objects.filter(is_delete=False).all()
    serializer_class = serializer.CarModelSerializer
    lookup_url_kwarg = 'pk'

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

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

    from rest_framework.settings import api_settings

    # 单查  群查
    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        if pk:
            return self.retrieve(request, *args, **kwargs)
        return self.list(request, *args, **kwargs)

    # 单增,
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        # headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=201)

    # 单局部改,
    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', True)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        car_obj = serializer.save()
        if getattr(instance, '_prefetched_objects_cache', None):
            instance._prefetched_objects_cache = {}
        return APIResponse(results=self.get_serializer(car_obj).data)

    
    
    # 单删接口
    def destroy(self, request, *args, **kwargs):
        car_obj = self.get_object()
        if not car_obj:
            return APIResponse(1, msg="删除失败")
        car_obj.is_delete = True
        car_obj.save()
        return APIResponse(msg="删除成功")
posted @ 2019-12-31 08:49  mqb11  阅读(100)  评论(0编辑  收藏  举报