如何使用Django Rest Framework删除对象

时间:2014-10-18 23:05:42

标签: python django rest django-rest-framework

我正在尝试使用Django Rest Framework为我的活动策划应用编写一个RESTful API,但是在使用不期望GET HTTP方法的视图时我遇到了一些麻烦。我已经阅读了DRF网站上的教程。根据我在阅读教程和Django网站上基于类的视图文档后的理解,如果有这样的基于类的视图(取自DRF教程)

class SnippetDetail(APIView):
    """
    Retrieve, update or delete a snippet instance.
    """
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        snippet = self.get_object(pk)
        serializer = SnippetSerializer(snippet, data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

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

视图中的不同方法对应于不同的HTTP Request方法。因此,如果我有www.foo.com/bar,它会根据发送到该地址的请求方法执行两项不同的操作。这意味着我不必指定任何其他内容,因为执行的函数是根据发送URL的方法确定的。这是对的吗?

我有这个视图,我试图在DRF网站上的示例之后建模

class EventDetail(APIView):

    """
    Retrieve, update or delete a event instance.
    """

    def get_object(self, pk):
        try:
            return Event.objects.get(pk=pk)
        except Event.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        event = self.get_object(pk)
        serializer = EventSerializer(event)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = EventSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    # def put(self, request, pk, format=None):
    #     event = self.get_object(pk)
    #     serializer = EventSerializer(event, data=request.DATA)
    #     if serializer.is_valid():
    #         serializer.save()
    #         return Response(serializer.data)
    #     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

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

映射到这些网址

urlpatterns = patterns('',

                       # Get event
                       url(r'^(?P<pk>\d+)/$', views.EventDetail.as_view(),
                           name='create_events'),
                       # list all events
                       url(r'^list/$', views.EventList.as_view(),
                           name='list_events'),
                       # url(r'^update$/(?P<pk>\d+)', #update event),
                       url(r'^create/$', views.EventDetail.as_view(),
                           name='create_events'),
                       # delete event
                       url(r'^delete$/(?P<pk>\d+)',
                           views.EventDetail.as_view(), name='delete_event'),

                       )

我试图使用CURL使用此命令进行测试(如此处DELETE using CURL with encoded URL建议的那样)

curl -X DELETE "http://127.0.0.1:8000/events/delete/1"

这似乎应该做到:

[18/Oct/2014 22:41:27] "DELETE /events/delete/1 HTTP/1.1" 404 2707

但实际记录不会从我的数据库中删除

这里有什么我忘记做的事情才能让它正常工作吗?

2 个答案:

答案 0 :(得分:21)

你是多余的。 HTTP方法已经DELETE,因此网址中没有/events/delete。试试这个:

curl -X DELETE "http://127.0.0.1:8000/events/1/"

默认情况下,DRF的路由器会在/event/<pk>创建详细的网址,您GETPUTPOSTDELETE要检索这些网址,分别更新,创建和删除。

答案 1 :(得分:2)

正如Kevin Stone所提到的那样,你使用的模式是不可取的,但是如果你想使用它,你需要在你的网址中修复 events / delete / mapping。

 # delete event
 url(r'^delete$/(?P<pk>\d+)',
     views.EventDetail.as_view(), name='delete_event'),

应该是:

 # delete event
 url(r'^delete/(?P<pk>\d+)',
     views.EventDetail.as_view(), name='delete_event'),