Django rest framework批量删除

使用ModelViewSet可以自动生成删除单个资源的方法,删除的url是/resource_name/pk/。如果想要批量删除可以写继承APIView的类,自定义delete方法,如果使用ModelViewSet的话可以在类里面写一个批量删除的函数:

from rest_framework.decorators import action
class ButtonViewset(viewsets.ModelViewSet):
    """
    按钮
    """
    permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
    serializer_class = ButtonSerializer
    queryset = Button.objects.all()
    authentication_classes = (JSONWebTokenAuthentication, authentication.SessionAuthentication)
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = ButtonFilter
    pagination_class = CommPagination
    ordering_fields = ('sort',)
    ordering = ('sort',)

    @action(methods=['delete'], detail=False)
    def multiple_delete(self, request, *args, **kwargs):
        """
        api/pc/button/multiple_delete/?deleteid=1,2,3
        :param request:
        :param args:
        :param kwargs:
        :return:
        """
        delete_id = request.query_params.get('deleteid', None)
        if not delete_id:
            return Response(status=status.HTTP_404_NOT_FOUND)
        btn_ids = delete_id.split(',')
        btn_ids = [int(x) for x in btn_ids if x.split()]
        buttons = Button.objects.filter(id__in=btn_ids).delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

注意:
action装饰器使multiple_delete方法接受delete操作,detail=False使得在users/后面直接跟方法名而不用加/pk/
api/pc/button/multiple_delete/?deleteid=1,2,3

你可能感兴趣的:(Django rest framework批量删除)