原网址
使用类来代替视图函数
views.py
from rest_framework.views import APIView
class Test(APIView)
def get()
urls.py # 转化为view函数
Test.as_view()
视图中新增get_object方法 来给get put delete等方法使用
def get_object(self,pk):
try:
return Quick.objects.get(pk=pk)
except Quick.DoesNotExist:
raise Http404
使用mixin简化代码
from rest_framework import mixins
from rest_framework import generics
class SnippetList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
进一步优化
from rest_framework import generics
class SnippetList(generics.ListCreateAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
class SnippetDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Snippet.objects.all()
serializer_class = SnippetSerializer
一个model的create一般是放在了list之中而不是放在detail视图中