如何删除Django Rest Api中的集合?

时间:2014-06-03 06:33:23

标签: python django django-rest-framework

我现在已经尝试了一段时间来“删除”'在Django Api View中阅读集合时工作。我一直在使用' ListCreateAPIView'并且只提供get和post方法处理程序。有谁知道如何解决这个问题?

我的观点:

class NotepadDetail(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'])

3 个答案:

答案 0 :(得分:3)

通过添加:

来解决它
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)

答案 1 :(得分:1)

您可以使用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)

self.destroy提供的DestroyModelMixin方法将处理对象删除,将正确引发pre_deletepost_delete信号,并返回204 NO CONTENT状态。

答案 2 :(得分:0)

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