我正在尝试在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终点: - localhost/itemlist
如果我们GET localhost/itemlist
它会返回项目列表。
如果我们POST localhost/itemlist
包含字段item_1
,item_2
,item_3
,则会创建该行。
现在,我想使用PUT
更新特定行。比如,如果我想要更新item_3
item_1 == "test1"
DELETE应删除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)
答案 0 :(得分:1)
使用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')),
]
然后你应该能够发送put和delete请求。这适用于Django 1.9x。
还有一件事:请阅读Python Style Guide。我们通常使用CamelCase作为类名。