rest_framework(六)
目录
视图家族
视图类(views)
APIView
- 拥有view的所有功能
- 重写as_view,局部禁用csrf
- 重写dispatch
- 一系类列属性(局部全局配置)
GenericAPIView
该类下主要使用:get_object, get_query, get_serializer
- 继承APIView,所以拥有APIView的所有
- get_queryset方法,配置queryset类属性,提供视图类相关的Models
- 在第二条基础上,get_object方法,配置lookup_url_kwarg类属性,提供视图类相关的具体Model
- get_serializer方法,配置serializer_class类属性,提供视图类相关的序列化对象
单查群查
from rest_framework.generics import GenericAPIView
class CarGenericAPIView(GenericAPIView):
#该返回值一定要是query对象,如果object后面不加.query方法,是manager对象
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
# 源码中默认设置路由参数名lookup_url_kwarg为pk,可以自定义
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)
#单查
def get(self,request,*args,**kwargs):
# pk = kwargs.get('pk')
# car_obj = models.Car.objects.filter(is_delete=False).filter(pk=pk).first()
# car_ser = serializers.CarModelSerializer(car_obj)
car_obj = self.get_object()
car_ser = self.get_serializer(car_obj)
return APIResponse(results=car_ser.data)
视图工具类(mixins)
CreateModelMixin
ListModelMixin
RetrieveModelMixin
UpdateModelMixin
DestroyModelMixin
单查群查(RetrieveModelMixin,ListModelMixin)
from rest_framework.mixins import RetrieveModelMixin,ListModelMixin
#mixins视图工具类
class CarReadGenericAPIView(ListModelMixin,RetrieveModelMixin,GenericAPIView):
#该返回值一定要是query对象,如果object后面不加.query方法,是manager对象
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
# 源码中默认设置路由参数名lookup_url_kwarg为pk,可以自定义
lookup_url_kwarg = 'pk'
#群查
def get(self,request,*args,**kwargs):
response = self.list(request,*args,**kwargs)
return APIResponse(results=response.data)
#单查
def get(self,request,*args,**kwargs):
# car_obj = self.get_object()
# car_ser = self.get_serializer(car_obj)
# return APIResponse(results=car_ser.data)
response = self.retrieve(request, *args, **kwargs)
return APIResponse(results=response.data)
单增(CreateModelMixin)
from rest_framework.mixins import RetrieveModelMixin,ListModelMixin,CreateModelMixin
#mixins视图工具类
class CarReadGenericAPIView(ListModelMixin,RetrieveModelMixin,CreateModelMixin,GenericAPIView):
#该返回值一定要是query对象,如果object后面不加.query方法,是manager对象
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
# 源码中默认设置路由参数名lookup_url_kwarg为pk,可以自定义
lookup_url_kwarg = 'pk'
#单增
def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)
#--------------------------------------------------------
#单增时需要设置哪些字段是需要参与反序列化(子序列化无法完成反序列化)
class SponsorModelSerializer(serializers.ModelSerializer):
class Meta:
model = models.Sponsor
fields = ('name', 'phone')
class CarModelSerializer(serializers.ModelSerializer):
# sponsors = SponsorModelSerializer(many=True) # 用子序列化完成外键,外键就不能参与反序列化
class Meta:
model = models.Car
fields = ('name', 'price', 'brand_name', 'sponsor_list', 'brand', 'sponsors')
extra_kwargs = {
'brand': {
'required': True,
'write_only': True
},
'sponsors': {
'required': True,
'write_only': True
},
}
九大工具视图类(generics)
ListCreateAPIView(群查和单增)
RetrieveAPIView(单查)
RetrieveDestroyAPIView(单查单删)
RetrieveUpdateAPIView(单查单改)
RetrieveUpdateDestroyAPIView(单查,单改,单删)
UpdateAPIView(单改)
单查接口(RetrieveAPIView)
在RetrieveAPIView类内有get方法,该方法封装了单查方法
#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'
群查接口(ListAPIView)
在ListAPIView类内有get方法,该方法封装了群查方法
#单独完成单查接口
from rest_framework.generics import ListAPIView
class CarListAPIView(ListAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
RetrieveUpdateDestroyAPIView(单查,单整体改,单局部改,单删接口)
#单查(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
generics类总结
-
APIView
- 拥有view的所有功能
- 重写as_view,局部禁用csrf
- 重写dispatch
- 一系类列属性(局部全局配置)
-
GenericAPIView
- 继2承APIView,所以拥有APIView的所有
- get_queryset方法,配置queryset类属性,提供视图类相关的Models
- 在第二条基础上,get_object方法,配置lookup_url_kwarg类属性,提供视图类相关的具体Model
- get_serializer方法,配置serializer_class类属性,提供视图类相关的序列化对象
''' 总结: GenericAPIView就是在APIView基础上额外提供了三个方法,三个类属性,如果不配合视图工具类,体现不出优势 目的: 视图中的增删改查逻辑相似,但操作的资源不一致,操作资源就是操作 资源对象们、资源对象以及资源相关的序列化类, 将这三者形成配置,那操作逻辑就一致,就可以进行封装 '''
-
mixins视图工具类们:五个类,六个方法
''' 要配合GenericAPIView类使用,将单查、群查、单增,单整体改,单局部改,单删六个接口 封装成retrieve、list、create、update、partial_update、destroy六个方法 原因: 六个方法的实现体,调用的方法就是GenericAPIView提供的,所以要配合GenericAPIView类使用 '''
-
generics工具视图类们:九种组合
- 帮我们将不同个数不同种类的mixins与GenericAPIView进行组合
- 不同的组合帮我们实现好对应的get、post、put、patch、delete方法
- 需要我们自己配置三个类属性即可:queryset、serializer_class、lookup_url_kwarg
视图集(viewsets)
两个视图集基类:GenericViewSet和ViewSet
两个视图集子类:ReadOnlyModelViewSet,ModelViewSet
一个工具类
ViewSetMixin
在ViewSetMixin类中重写了as_view方法,将as_view中的参数(方法名)直接映射称对应的函数,并执行
单查群查共存
#单查群查共存
from rest_framework.viewsets import ViewSetMixin,GenericViewSet,ViewSet
class CarReadOnlyAPIView(RetrieveModelMixin,ListModelMixin,GenericViewSet):
# def many_get(self,request,*args,**kwargs):
# return self.list(request,*args,**kwargs)
#
# def single_get(self,request,*args,**kwargs):
# return self.retrieve(request,*args,**kwargs)
#路由中,直接反射list和retrieve方法
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSerializer
六大接口
#路由配置
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',
})),
# 六大接口
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
# destroy方法是完成is_delete字段值修改 - 重写destroy方法,自定义实现体
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)
路由层
# 路由层:
from rest_framework.routers import SimpleRouter
router = SimpleRouter()
router.register('v7/cars', views.CarModelViewSet, basename='car')
router.register('books', views.BookModelViewSet, basename='book')
router.register('users', views.UserModelViewSet, basename='user')
urlpatterns = [
'''
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',
})),
'''
#分发
url(r'', include(router.urls))
]
视图总结
'''
核心:视图集都继承了 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两个视图集子类,就是做个一堆mixin与GenericViewSet相结合,
自己在urls文件中配置as_view设置映射关系
'''