[Django]-How do I delete a collection in Django Rest Api?

4👍

Solved it by adding:

def get_object(self, notepad_pk):
    try:
        return Notepad.objects.get(user=self.request.user, pk=notepad_pk)
    except Notepad.DoesNotExist:
        raise Http404

def delete(self, request, notepad_pk, format=None):
    object = self.get_object(notepad_pk)
    object.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)

2👍

You can use a DestroyModelMixin:

class NotepadDetail(generics.DestroyModelMixin,
                    generics.ListCreateAPIView):
    model = Session
    serializer_class = SessionSerializer

    def get_queryset(self):
        user=self.request.user
        notepad = self.kwargs['notepad_pk']
        return Session.objects.filter(user=user, notepad=notepad)

    def pre_save(self, obj):
        obj.user = self.request.user
        obj.notepad = get_object_or_404(Notepad, user=self.request.user, pk=self.kwargs['notepad_pk'])

    def delete(self, request, *args, **kwargs):
        return self.destroy(request, *args, **kwargs)

The self.destroy method provided by the DestroyModelMixin will handle the object deletion, will correctly raise the pre_delete and post_delete signals, and will return the 204 NO CONTENT status.

0👍

def delete(self, request, pk, format=None):
           event = self.get_object(pk)
           event.delete()
           return Response("Object Deleted")

Leave a comment