我们上一篇博客讲解了如何使用mixins类实现rest_framework的视图,但是其中有很多的冗余的代码,我们这边在来优化一下
1、queryset的视图函数
首先看下对queryset操作的视图类是怎么写的
from rest_framework import mixins from rest_framework import generics class Auther_view(generics.ListCreateAPIView): queryset = models.Auther.objects.all() serializer_class = authermodelserializer
直接这样写就ok了,为什么呢?我们来看下generics.ListCreateAPIView类,不仅仅继承了我们之前写的3个类,还帮我们写了get和post方法,所以我们直接用上面的方法就是mixin类中的效果
class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): """ Concrete view for listing a queryset or creating a model instance. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs)
2、model对象的视图
类只需要继承generics.RetrieveUpdateDestoryAPIView在一个类就可以了
class Autherdetail_view(generics.RetrieveUpdateDestroyAPIView): queryset = models.Auther.objects.all() serializer_class = authermodelserializer
这个类generics.RetrieveUpdateDestoryAPIView同样继承了我们我们想要的其他四个类,而且还帮我们重写了get、delete、put方法
class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving, updating or deleting a model instance. """ 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 patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs)
至此,基于通用类实现rest_framework的视图就讲解完了