Reputation: 237
I am trying to implement simple CRUD operation in Django Rest. I have successfully created, GET
and POST
. Now, I want to update the row data with PUT
and delete a row with DELETE
.
Currently, my table looks like :-
id item_1 item_2 item_3 date_created date_modified
1 test1 test2 test3 16-12-2017 16-12-2017
2 ex1 ex2 ex3 16-12-2017 16-12-2017
API End point :- localhost/itemlist
If we GET localhost/itemlist
it returns the list of items.
If we POST localhost/itemlist
with fields item_1
, item_2
, item_3
, it creates the row.
Now, I want to use PUT
to update a particular row. Like, if I want to update the value of item_3
where item_1 == "test1"
DELETE should delete the row where item_1 == ex1
urls.py
from django.conf.urls import url, include
from rest_framework.urlpatterns import format_suffix_patterns
from .views import ItemView
urlpatterns = {
url(r'^itemlists/$', ItemView.as_view(), name="create"),
}
urlpatterns = format_suffix_patterns(urlpatterns)
views.py :
from rest_framework import generics
from .serializers import itemlistSerializer
from .models import itemlist
class ItemView(generics.ListCreateAPIView):
queryset = itemlist.objects.all()
serializer_class = itemlistSerializer
def perform_create(self, serializer):
serializer.save()
serializers.py
from rest_framework import serializers
from .models import itemlist
class itemlistSerializer(serializers.ModelSerializer):
class Meta:
"""Meta class to map serializer's fields with the model fields."""
model = itemlist
fields = ('id', 'item_1', 'item_2', 'item_3', 'date_created', 'date_modified')
read_only_fields = ('date_created', 'date_modified')
models.py
from django.db import models
class itemlist(models.Model):
"""This class represents the itemlist model."""
item_1 = models.CharField(max_length=255, blank=True, unique=False)
item_2 = models.CharField(max_length=255, blank=True, unique=False)
item_3 = models.CharField(max_length=255, blank=True, unique=False)
date_created = models.DateTimeField(auto_now_add=True)
date_modified = models.DateTimeField(auto_now=True)
def __str__(self):
"""Return a human readable representation of the model instance."""
return "{}".format(self.item_1)
Upvotes: 0
Views: 789
Reputation: 4634
Use django viewsets:
viewsets.py
class ListItemViewSet(viewsets.ModelViewSet):
serializer_class = itemlistSerializer
queryset = itemlist.objects.all()
http_method_names = ['get', 'post', 'put', 'delete', 'option']
def get_queryset(self):
request_user = self.request.user
if not request_user.is_superuser:
return self.queryset.filter(owner=request_user)
urls.py
router = routers.DefaultRouter()
router.register(listitem', ListItemViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
Then you should be able to send put and delete requests. This works for Django 1.9x.
Just one more thing: Please read the Python Style Guide. We normally use CamelCase for class names.
Upvotes: 1