rest-framework視圖組件
方法一:基本視圖
路由配置:
url(r'^publish/$', views.PublishView.as_view()),
url(r'^publish/(?P<pk>\d+)/$', views.PublishDetailView.as_view()),
視圖層:
class PublishSerializers(serializers.ModelSerializer):
class Meta:
model=models.Publish
fields='__all__'
class PublishView(APIView):
def get(self, request):
publish_list = models.Publish.objects.all()
bs = PublishSerializers(publish_list, many=True)
# 序列化數(shù)據(jù)
return Response(bs.data)
def post(self, request):
# 添加一條數(shù)據(jù)
print(request.data)
bs=PublishSerializers(data=request.data)
if bs.is_valid():
bs.save() # 生成記錄
return Response(bs.data)
else:
return Response(bs.errors)
class PublishDetailView(APIView):
def get(self,request,pk):
publish_obj=models.Publish.objects.filter(pk=pk).first()
bs=PublishSerializers(publish_obj,many=False)
return Response(bs.data)
def put(self,request,pk):
publish_obj = models.Publish.objects.filter(pk=pk).first()
bs=PublishSerializers(data=request.data,instance=publish_obj)
if bs.is_valid():
bs.save() # update
return Response(bs.data)
else:
return Response(bs.errors)
def delete(self,request,pk):
models.Publish.objects.filter(pk=pk).delete()
return Response("")
方法二: mixin類和generice類編寫視圖
from rest_framework.mixins import CreateModelMixin,RetrieveModelMixin,ListModelMixin,UpdateModelMixin,DestroyModelMixin
from rest_framework.generics import GenericAPIView
class PublishView(ListModelMixin,CreateModelMixin,GenericAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers
def get(self, request):
return self.list(request)
def post(self, request):
return self.create(request)
class PublishDetailView(RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin,GenericAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers
def get(self,request,*args,**kwargs):
return self.retrieve(request,*args,**kwargs)
def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)
def delete(self,request,*args,**kwargs):
return self.destroy(request,*args,**kwargs)
方法三:使用generics 下ListCreateAPIView等進(jìn)一步封裝
from rest_framework.generics import ListCreateAPIView,RetrieveUpdateDestroyAPIView
class PublishView(ListCreateAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers
class PublishDetailView(RetrieveUpdateDestroyAPIView):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers
方法四:使用ModelViewSet(不推薦使用)
封裝的越好呻此,可擴(kuò)展性越差
路由:
url(r'^publish/$', views.PublishView.as_view({'get':'list','post':'create'})),
url(r'^publish/(?P<pk>\d+)/$', views.PublishView.as_view({'get':'retrieve','put':'update','delete':'destroy'})),
視圖:
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):
queryset=models.Publish.objects.all()
serializer_class=PublishSerializers