本文主要是介绍茴香豆的四种写法(rest-framework之视图),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一.基本视图
基本视图继承APIView,所以里面的方法都需要我们自己重写。
基本视图
class PublishView(APIView):def get(self, request):publish_list = models.Publish.objects.all()bs = PublishSerializers(publish_list, many=True)# 序列化数据return Response(bs.data)def post(self, request):# 添加一条数据print(request.data)bs=PublishSerializers(data=request.data)if bs.is_valid():bs.save() # 生成记录return Response(bs.data)else:return Response(bs.errors)
二.基于mixins来封装的视图
基于mixins来封装的视图
from rest_framework.mixins import CreateModelMixin,ListModelMixin,RetrieveModelMixin,DestroyModelMixin,UpdateModelMixin
from rest_framework.generics import GenericAPIViewclass PublishView(CreateModelMixin,ListModelMixin,GenericAPIView):queryset = models.Publish.objects.all()serializer_class = PublishSerializersdef post(self,request, *args, **kwargs):return self.create(request, *args, **kwargs)def get(self,request, *args, **kwargs):return self.list(request, *args, **kwargs)
mixins封装了5个方法:
上图类中对应的方法:create(新增),destory(删除),list(查询多条信息),retrieve(查询一条信息),update(更新保存)
三.第三种写法(5合2接口)
第三种写法
from rest_framework.generics import CreateAPIView,ListCreateAPIView,DestroyAPIView,RetrieveUpdateDestroyAPIView
class PublishView(ListCreateAPIView):queryset = models.Publish.objects.all()serializer_class = PublishSerializersclass PublishDetailView(RetrieveUpdateDestroyAPIView):queryset = models.Publish.objects.all()serializer_class = PublishSerializers
generics模块里的类及相对应的方法
四.第四种写法(5合1接口)
# 第四种写法
#5个接口写在一个类中from django.views import View
from rest_framework.viewsets import ModelViewSet
class PublishView(ModelViewSet):queryset=models.Publish.objects.all()serializer_class=PublishSerializers
viewsets 所有的方法:
ModelViewSet继承了mixins的所有方法:
所有可用方法。
这篇关于茴香豆的四种写法(rest-framework之视图)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!