Django rest framework: how to make a view to delete multiple objects? #8356
-
Hi. I have another noobish question that I posted to SO. Trying to create a view with a form that would allow me to delete multiple objects at once. Is that possible/straightforward with DRF? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You've already go the right approach in your SO question. If you wanted the same sort of thing, but based on the generic class based views, then you'd probably want something like this... class ListOrBulkDelete(GenericAPIView):
def get(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
def delete(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
queryset.delete() # CAREFUL! This could easily delete all the items in this queryset.
# You might want some additional checking
return Response(status=status.HTTP_204_NO_CONTENT) Which you could then reuse anywhere you needed a list or bulk delete... class AlbumListOrBulkDelete(ListOrBulkDelete):
filter_class = ... # See https://www.django-rest-framework.org/api-guide/filtering/
queryset = ... Personally I probably wouldn't rely on the generic views. I'd just keep things a bit more direct. For example... class ListOrBulkDeleteAlbums(APIView):
def get(self, request, *args, **kwargs):
ids = request.query_params.get('ids').split(',')
queryset = Album.objects.filter(id__in=ids)
serializer = AlbumSerializer(queryset, many=True)
return Response(serializer.data)
def delete(self, request, *args, **kwargs):
ids = request.query_params.get('ids').split(',')
if ids:
queryset = Album.objects.filter(id__in=ids)
queryset.delete()
return Response(status=status.HTTP_204_NO_CONTENT) You wouldn't end up with a form for selecting the Albums, but the code flow is more obvious. |
Beta Was this translation helpful? Give feedback.
You've already go the right approach in your SO question.
If you wanted the same sort of thing, but based on the generic class based views, then you'd probably want something like this...