Python Django REST中的UPDATE和DELETE操作

时间:2017-12-15 22:40:48

标签: python django rest crud

我正在尝试在Django Rest中实现简单的CRUD操作。我已成功创建GETPOST。现在,我想用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_1item_2item_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)

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作为类名。