简体   繁体   中英

Delete/Destroy/Update list using Django REST API View

I created a serializer and class ExampleUpdateView in views.py to delete or update an item in my database:

serializer.py:

from rest_framework import serializers
from example.models import Example
from django.contrib.auth.models import User

class ExampleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Example

views.py:

class ExampleUpdateView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Example.objects.all()
    serializer_class = ExampleSerializer

urls.py:

from django.conf.urls import patterns, url,include
from rest_framework.urlpatterns import format_suffix_patterns
from example import views

urlpatterns = patterns('',
    url(r'^example/(?P<pk>[0-9]+)/$', views.ExampleUpdateView.as_view()),
)

Everything works fine, I can update and delete items from list using APIView. Maybe it is a little bit stupid question, but I am curios about how to delete or update using url. For example "...url../example?delete=5" to delete item with primary key 5 or "...url../example?update=5&description="updated"" for updating the item. Is it possible using API View?

Could somebody help me please?

The principle of REST is to follow HTTP.

If you make something like "...url../example?delete=5" you would make GET request. GET is not for deleting, updating, creating. If you send GET request, it will retrieve, if you send PUT request it will update. The verbs are not part of the URL, so what you want to do with the URL parameters is not REST at all.

If the browsable API is not enough, you can check also some other tools. I use the chrome-extension REST Console:

https://chrome.google.com/webstore/detail/rest-console/cokgbflfommojglbmbpenpphppikmonn?hl=en

You can use curl in the bash to send different requests. For python there is a very nice library called requests :

http://docs.python-requests.org/en/latest/

If you use a default router and a ModelViewSet you just have to make a request to the API using the HTTP methods to update or delete respectively. Yo can also override the default methods list() , retrieve() , create() , update() , and destroy() , provided by default.

For more information see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM