我试图在Django Rest中实现简单的CRUD操作。我已经成功创建了GET
和POST
。现在,我想用PUT
更新行数据并用DELETE
删除一行。
目前,我的表格如下: -
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端点: - qazxsw poi
如果我们localhost/itemlist
它返回项目列表。
如果我们GET localhost/itemlist
与字段POST localhost/itemlist
,item_1
,item_2
,它创建行。
现在,我想使用item_3
更新特定行。就像,如果我想更新PUT
的item_3
的值
DELETE应删除item_1 == "test1"
所在的行
URLs.朋友
item_1 == ex1
views.朋友 :
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)
serialize认识.朋友
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()
models.朋友
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')
使用django viewsets:
views ETS.朋友
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)
URLs.朋友
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)
然后你应该能够发送put和delete请求。这适用于Django 1.9x。
还有一件事:请阅读router = routers.DefaultRouter()
router.register(listitem', ListItemViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
。我们通常使用CamelCase作为类名。