drf接口-自己写的继承APIView编写books 5个接、继承APIView,有两个类属性、基于5个视图扩展类、通过9个视图子类编写接口、视图集

一、第一层,我们自己写的,继承APIView编写books 5个接口

1.路由
	path('books/', BookView.as_view()),
    path('books//', BookDetailView.as_view()),
    
	path('publish/', PublishView.as_view()),
    path('publish//', PublishDetailView.as_view()),

2.serializer类
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = '__all__'

3.视图函数
class BookView(APIView):
    def get(self, request):
        book = Book.objects.all()
        ser = BookSerializer(instance=book, many=True)
        # ser.data 做了个序列化
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})

    def post(self, request):
        ser = BookSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '新增成功', 'data': ser.data})
        return Response({'code': 201, 'msg': '查询失败', 'data': ser.errors})


class BookDetailView(APIView):
    def get(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(instance=book)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})

    def put(self, request, pk):
        book = Book.objects.filter(pk=pk).first()
        ser = BookSerializer(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '修改成功', 'data': ser.data})
        return Response({'code': 201, 'msg': '修改失败', 'data': ser.errors})

    def delete(self, request, pk):
        Book.objects.filter(pk=pk).delete()
        return Response('')


from .serializer import PublishSerializer
from .models import Publish


class PublishView(APIView):
    def get(self, request):
        obj_list = Publish.objects.all()
        ser = BookSerializer(instance=obj_list, many=True)
        # ser.data 做了个序列化
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})

    def post(self, request):
        ser = PublishSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '新增成功', 'data': ser.data})
        return Response({'code': 201, 'msg': '查询失败', 'data': ser.errors})


class PublishDetailView(APIView):
    def get(self, request, pk):
        obj = Publish.objects.filter(pk=pk).first()
        ser = PublishSerializer(instance=obj)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})

    def put(self, request, pk):
        book = Publish.objects.filter(pk=pk).first()
        ser = PublishSerializer(instance=book, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '修改成功', 'data': ser.data})
        return Response({'code': 201, 'msg': '修改失败', 'data': ser.errors})

    def delete(self, request, pk):
        Publish.objects.filter(pk=pk).delete()
        return Response('')

二、第二层,继承APIView,有两个类属性

1.路由
	path('publish/', PublishView.as_view()),
    path('publish//', PublishDetailView.as_view()),

2.serializer类
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = '__all__'

3.视图函数
class GenericAPIView(APIView):
    queryset = None
    serializer_class = None

    def get_queryset(self):
        return self.queryset.all()  # 真正使用的时候,在加all获取所有

    def get_serializer(self, *args, **kwargs):
        return self.serializer_class(*args, **kwargs)

    def get_object(self, pk):
        return self.get_queryset().filter(pk=pk).first()


#### drf提供的
from rest_framework.generics import GenericAPIView


class PublishView(GenericAPIView):
    queryset = Publish.objects.all()  # 类只要加载就会执行
    serializer_class = PublishSerializer

    def get(self, request):
        obj_list = self.get_queryset()
        ser = self.get_serializer(instance=obj_list, many=True)
        # ser.data 做了个序列化
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})

    def post(self, request):
        ser = self.get_serializer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '新增成功', 'data': ser.data})
        return Response({'code': 201, 'msg': '查询失败', 'data': ser.errors})


class PublishDetailView(GenericAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

    # 一般不建议这样写,就用 GenericAPIView 里面的
    # lookup_field = 'id'

    def get(self, request, pk):
        # 我们自己写的
        # obj = self.get_object(pk=pk)
        # drf 提供的不需要传pk进来
        obj = self.get_object()
        ser = self.get_serializer(instance=obj)
        return Response({'code': 200, 'msg': '查询成功', 'data': ser.data})

    # def get_serializer_class(self):
    #     if self.request.method == 'get':
    #         return self.serializer_class
    #     else:
    #         return '自己在写个序列化'

    def put(self, request, pk):
        # 我们自己写的
        # obj = self.get_object(pk=pk)
        # drf 提供的 不需要传pk进来
        obj = self.get_object()
        ser = self.get_serializer(instance=obj, data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200, 'msg': '修改成功', 'data': ser.data})
        return Response({'code': 201, 'msg': '修改失败', 'data': ser.errors})

    def delete(self, request, pk):
        # 我们自己写的
        # self.get_queryset().filter(pk=pk).delete()
        # drf 自带的
        self.get_object().delete()
        return Response('')

三、第三层 基于5个视图扩展类

1.路由
	path('publish/', PublishView.as_view()),
    path('publish//', PublishDetailView.as_view()),

2.serializer类
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = '__all__'

3.视图函数
from rest_framework.mixins import RetrieveModelMixin, CreateModelMixin, DestroyModelMixin, ListModelMixin, \
    UpdateModelMixin
# RetrieveModelMixin, 查询一条
# CreateModelMixin, 新增
# DestroyModelMixin, 删除
# ListModelMixin, 查询所有
# UpdateModelMixin, 修改

from rest_framework.generics import GenericAPIView
from .models import Publish
from .serializer import PublishSerializer


class PublishView(GenericAPIView, ListModelMixin, CreateModelMixin):
    queryset = Publish.objects.all()  # 类只要加载就会执行
    serializer_class = PublishSerializer

    def get(self, request):
        return self.list(request=request)

    def post(self, request):
        # 不要忘记return出去,也可以使用super
        # return self.create(request=request)
        return super().create(request=request)


class PublishDetailView(GenericAPIView, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

    def get(self, request, pk):
        return self.retrieve(request=request, pk=pk)

    def put(self, request, pk):
        return self.update(request=request, pk=pk)

    def delete(self, request, pk):
        return self.destroy(request=request, pk=pk)

四、第四层,通过9个视图子类编写接口

1.路由
	path('publish/', PublishView.as_view()),
    path('publish//', PublishDetailView.as_view()),

2.serializer类
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = '__all__'

3.视图函数
from rest_framework.generics import ListAPIView, CreateAPIView, ListCreateAPIView

from .models import Publish
from .serializer import PublishSerializer

# 1. GenericAPIView + ListModelMixin = ListAPIView

# class ListAPIView(GenericAPIView, ListModelMixin):
#     def get(self, request):
#         return self.list(request)

# 2. GenericAPIView + CreateModelMixin = CreateAPIView

# 3. GenericAPIView + ListModelMixin + CreateModelMixin = ListCreateAPIView

from rest_framework.generics import RetrieveAPIView, DestroyAPIView, UpdateAPIView
from rest_framework.generics import RetrieveUpdateDestroyAPIView, RetrieveDestroyAPIView, RetrieveUpdateAPIView


# 想写 publish:查询所有:查询单条,修改一条,新增一条,删除一条的接口
class PublishView(ListCreateAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer


class PublishDetailView(RetrieveUpdateDestroyAPIView):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer


# 想写 publish:查询所有:查询单条,修改一条,新增一条,删除一条的接口 ----> 使用5个视图扩展类 + GenericAPIView 编写res
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin, UpdateModelMixin, \
    DestroyModelMixin, RetrieveModelMixin, ListModelMixin


class PublishView(GenericAPIView, CreateModelMixin):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

    # post中的 *args接收任意长度的位置参数  **kwargs接收关键字参数
    def post(self, request, *args, **kwargs):
        # create中的 *args是把列表打散了传入  **kwargs是把字典打散了传入
        return self.create(request, *args, **kwargs)


class PublishDetailView(GenericAPIView, RetrieveModelMixin):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)


五、第五层,视图集

1.路由
	path('publish/', PublishView.as_view(actions={'get': 'list', 'post': 'create'})),
    path('publish//', PublishView.as_view(actions={'get': 'retrieve', 'put': 'update', 'delete': 'destroy'})),

2.serializer类
class PublishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = '__all__'

3.视图函数
from rest_framework.viewsets import ModelViewSet
from .models import Publish
from .serializer import PublishSerializer


class PublishView(ModelViewSet):
    queryset = Publish.objects.all()
    serializer_class = PublishSerializer

你可能感兴趣的:(django,python01,django,python,windows,pycharm,开发语言,restframework)