视图家族
views:视图类
APIView
1、拥有View的所有
2、重写as_view
3、重写dispatch
4、一系列类属性
GenericAPIView(generics中)
1、继承APIView,所以拥有APIView的所有
2、get_queryset方法,配置queryset类属性,提供视图类相关的Models
3、在第二条的基础上,get_object方法,配置lookup_url_kwarg类属性,提供视图类相关的具体Model
4、get_serializer方法,配置serializer_class类属性,提供视图类相关的序列化对象
总结:GenericAPIView就是在APIView基础上额外提供了三个方法,三个类属性,如果不配合视图工具类,体现不出优势
目的:视图中的增删改查逻辑相似,但操作的资源不一致,操作资源就是操作 资源对象们、资源对象、资源相关的序列化类,将这三者形成配置,那操作逻辑就一致,就可以进行封装
如果urls里是pk的话,lookup_url_kwarg默认就是pk,不用写,如果urls不是pk,lookup_url_kwargs就要写
from rest_framework.generics import GenericAPIView
class CarGenericAPIView(GenericAPIView):
#不能直接写到objects结束,因为objects结束时,不是Queryset对象,而是Manager对象,但是.all()和filter()后一定是Queryset对象
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class=serializers.CarModelSerializer
lookup_url_kwarg = 'pk'
#群查
def get(self,request,*args,**kwargs):
# car_query=models.Car.objects.filter(is_delete=False).all()
car_query=self.get_queryset()#等同于上一句
# car_ser=serializers.CarModelSerializer(instance=car_query,many=True)
car_ser=self.get_serializer(car_query,many=True)#等同于上一句
return APIResponse(results=car_ser.data)
#单查
def get(self,request,*args,**kwargs):
# pk=kwargs.get('pk')
# car_obj=models.Car.objects.filter(is_delete=False).filter(pk=pk).first()
car_obj=self.get_object()#等同于上两句
# car_ser=serializers.CarModelSerializer(car_obj)
car_ser=self.get_serializer(car_obj)#等同于上一句
return APIResponse(results=car_ser.data)
mixins:视图工具类
mixins视图工具类们:五个类,六个方法
CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
1、要配合GenericAPIView类使用,将单查、群查、单增、单整体改、单局部改、单删六个接口封装成retrieve、list、create、update、partial_update、destroy六个方法
原因:六个方法的实现体,调用的方法就是GenericAPIView提供的,所以要配合GenericAPIView类使用
单查群查不能同时存在
#mixins视图工具类
from rest_framework.mixins import RetrieveModelMixin,ListModelMixin,CreateModelMixin
class CarReadCreateGenericAPIView(ListModelMixin,RetrieveModelMixin,CreateModelMixin,GenericAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
lookup_url_kwarg = 'pk'
# 群查
def get(self, request, *args, **kwargs):
# car_query = self.get_queryset()
# car_ser = self.get_serializer(car_query, many=True) # 等同于上一句
# return APIResponse(results=car_ser.data)
return self.list(request,*args,**kwargs)
'''
#单查
def get(self, request, *args, **kwargs):
# car_obj = self.get_object()
# car_ser = self.get_serializer(car_obj)
# return APIResponse(results=car_ser.data)
return self.retrieve(request,*args,**kwargs)
#想返回APIResponse
# response=self.retrieve(request,*args,**kwargs)
# return APIResponse(response)
'''
#单增
def post(self, request, *args, **kwargs):
return self.create(request,*args,**kwargs)
generics:工具视图类
generics工具视图类们:九种组合
1、帮我们将不同个数不同种类的mixins与GenericAPIView进行组合
2、不同的组合帮我们实现好对应的get、post、put、patch、delete方法
3、需要我们自己配置三个类属性即可:queryset、serializer_class、lookup_url_kwarg
#Generics工具视图类
#单独完成单查接口
from rest_framework.generics import RetrieveAPIView
class CarRetrieveAPIView(RetrieveAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
lookup_url_kwarg = 'pk'
# 单独完成群查接口
from rest_framework.generics import ListAPIView
class CarListAPIView(ListAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
# 单查(get)、单整体改(put)、单局部改(patch)、单删接口(delete)
from rest_framework.generics import RetrieveUpdateDestroyAPIView
class CarRetrieveUpdateDestroyAPIView(RetrieveUpdateDestroyAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
viewsets:视图集
核心:视图集都继承了ViewSetMixin类,该类重写了as_view方法,相比APIView的as_view方法, 额外多出了一个参数actions,as_view({'get':'list'})传入的{'get':'list'}就被actions接收,原理是将get请求映射给视图类的list函数进行处理
1、为什么有GenericViewSet 和ViewSet两个视图集基类
GenericViewSet(ViewSetMixin, GenericAPIView),该分支严格满足资源接口
ViewSet(ViewSetMixin, APIView),该分支满足的接口与资源model类关系不是特别密切:登录接口、短信验证码接口
2、ReadOnlyModelViewSet,ModelViewSet两个视图子集,就是做了一堆minxin 与GenericViewSet 相结合,自己在urls文件中配置as_view设置映射关系
路由层
#视图集
url(r'^v6/cars/$', views.CarReadOnlyAPIView.as_view({'get':'list'})),
url(r'^v6/cars/(?P<pk>d+)/$', views.CarReadOnlyAPIView.as_view({'get':'retrieve'})),
视图层
#视图集
#单查 群查
from rest_framework.viewsets import ViewSetMixin,GenericViewSet,ViewSet,ModelViewSet
class CarReadOnlyAPIView(RetrieveModelMixin,ListModelMixin,GenericViewSet):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
视图层
# 六大接口
class CarModelViewSet(ModelViewSet):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
# 分析:从实际开发角度分析不合理点
#1、没有群增、群整体改、群局部改、群删四个接口
# 2、删除操作视图集默认走的destroy方法实际将资源从数据库中删除,通常一个做字段is_delete字段修改表示删除
#3、响应的结果只有数据,没有数据状态码和状态信息
#解决1:
#群整体改,群局部改,群删三个接口可以独立成三个方法
def many_update(self, request, *args, **kwargs):
return APIResponse(msg='这个地方是群整体改,你会写!')
def many_partial_update(self, request, *args, **kwargs):
return APIResponse(msg='这个地方是群局部改,你会写!')
def many_destroy(self, request, *args, **kwargs):
return APIResponse(msg='这个地方是群删,你会写!')
#群增与单增必须公用一个接口,都要走create方法-重写create方法,用逻辑进行拆分
def create(self, request, *args, **kwargs):
request_data=request.data
if isinstance(request_data,list):
car_ser=self.get_serializer(data=request_data,many=True)
car_ser.is_valid(raise_exception=True)
car_obj=car_ser.save()
return APIResponse(msg='群增成功',results=self.get_serializer(car_obj,many=True).data)
return super().create(request,*args,**kwargs)
#解决2:destory方法完成is_delete字段值修改-重写destory方法,自定义实现体
def destroy(self, request, *args, **kwargs):
car_obj=self.get_object()
car_obj.is_delete=True
car_obj.save()
return APIResponse(msg='删除成功')
#解决3:让群查有状态码和状态信息-重写list方法
def list(self,request,*args,**kwargs):
response=super().list(request,*args,**kwargs)
return APIResponse(results=response.data)
路由层
url(r'^v7/cars/$', views.CarModelViewSet.as_view({
'get':'list',
'post':'create',
'put':'many_update',
'patch': 'many_partial_update',
'delete': 'many_destroy',
})),
url(r'^v7/cars/(?P<pk>d+)/$', views.CarModelViewSet.as_view({
'get':'retrieve',
'put':'update',
'patch':'partial_update',
'delete':'destroy,
})),
router(了解)
#路由层:外面会遇到这种写法,看到了要认识
from rest_framework.routers import SimpleRouter
router=SimpleRouter()
router.register('v7/cars',views.CarModelViewSet,basename='car')
urlpatterns = [
url(r'',include(router.urls))
]