小火车 2019-11-10
在原来modelserializers基础上进行了一次封装方便了使用# author class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = models.Author fields = "__all__" from rest_framework import mixins from rest_framework import generics class AuthorView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class AuthorDetaiView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin, generics.GenericAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def delete(self,request,*args,**kwargs): return self.destroy(request,*args,**kwargs) def put(self,request,*args,**kwargs): return self.update(request,*args,**kwargs)
使用通用的基于类的视图(封装第三次减少了代码量)
# author class AuthorModelSerializers(serializers.ModelSerializer): class Meta: model = models.Author fields = "__all__" from rest_framework import mixins from rest_framework import generics # 封装了3层 class AuthorView(generics.ListCreateAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers # 封装了3层 class AuthorDetaiView(generics.RetrieveUpdateDestroyAPIView): # queryset serializer 这两个方法一定要定义成这个不然取不到值 queryset = models.Author.objects.all() serializer_class = AuthorModelSerializers使用视图集viewsets.ModelViewSet原理:
# authorclass AuthorModelSerializers(serializers.ModelSerializer):class Meta: model = models.Author fields = "__all__"from rest_framework import mixinsfrom rest_framework import genericsclass AuthorView(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):# queryset serializer 这两个方法一定要定义成这个不然取不到值queryset = models.Author.objects.all() serializer_class = AuthorModelSerializersdef get(self, request, *args, **kwargs):return self.list(request, *args, **kwargs)def post(self, request, *args, **kwargs):return self.create(request, *args, **kwargs)class AuthorDetaiView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, mixins.UpdateModelMixin,generics.GenericAPIView):# queryset serializer 这两个方法一定要定义成这个不然取不到值queryset = models.Author.objects.all() serializer_class = AuthorModelSerializersdef get(self, request, *args, **kwargs):return self.retrieve(request, *args, **kwargs)def delete(self,request,*args,**kwargs):return self.destroy(request,*args,**kwargs)def put(self,request,*args,**kwargs):return self.update(request,*args,**kwargs)