首先,我们需要在modelViewset中定义一个自定义的action,用于批量删除对象。例如:
from rest_framework.decorators import action
from rest_framework.response import Response
class MyModelViewset(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
@action(detail=False, methods=['delete'])
def batch_delete(self, request):
ids = request.query_params.get('ids', '').split(',')
self.queryset.filter(id__in=ids).delete()
return Response({'message': 'success.'})
在上面的代码中,我们使用了装饰器@action
来定义一个名为batch_delete
的自定义方法。我们使用了DELETE方法来触发该action。
action装饰器提供了以下参数:
- detail:指定该action方法是否针对单个实例进行操作。默认为True,表示该方法需要一个实例作为参数。如