标签:自己 直接 python upd view设置 pre require response 映射关系
from rest_framework import views, mixins, generics, viewsets
views:视图类 - APIView,GenericAPIView(generics中)
mixins:视图工具类 - CreateModelMixin,ListModelMixin,RetrieveModelMixin,UpdateModelMixin,DestroyModelMixin
generics:工具视图类 - 九个类
viewsets:视图集 - 两个视图集基类,两个视图集子类,一个工具类
class CarAPIView(APIView):
# 群查
def get(self, request, *args, **kwargs):
car_query = models.Car.objects.filter(is_delete=False).all()
car_ser = serializers.CarModelSerializer(instance=car_query, many=True)
return APIResponse(results=car_ser.data)
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):
# 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)
def retrieve(self, request, *args, **kwargs):
方法,可以快速返回一个存在的数据对象def list(self, request, *args, **kwargs):
方法,该list方法可以对数据过滤和分页def create(self, request, *args, **kwargs):
方法快速实现创建资源的视图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 post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
Generics工具视图类(七个功能视图子类)
class RetrieveAPIView(mixins.RetrieveModelMixin,
GenericAPIView)
提供get方法
class ListAPIView(mixins.ListModelMixin,
GenericAPIView):
提供get方法
class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
GenericAPIView):
提供get、put、patch、delete方法
serializer_class 指明视图使用的序列化器
# 单独完成单查接口
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
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',
})),
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'', include(router.urls))]
print(router.urls)
# 六大接口
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):
request_data = request.data
try:
pks = []
for dic in request_data:
pk = dic.pop('pk')
pks.append(pk)
car_query = self.get_queryset()
if len(pks) != len(car_query):
raise Exception('pk对应的数据不存在')
except Exception as e:
return Response({'detail': '%s' % e}, status=400)
car_ser = self.get_serializer(instance=car_query, data=request_data, many=True)
car_ser.is_valid(raise_exception=True)
car_list = car_ser.save()
return APIResponse(msg='群整体改成功', results=self.get_serializer(car_list, many=True).data)
def many_partial_update(self, request, *args, **kwargs):
request_data = request.data
try:
pks = []
for dic in request_data:
pk = dic.pop('pk')
pks.append(pk)
car_query = self.get_queryset()
if len(pks) != len(car_query):
raise Exception('pk对应的数据不存在')
except Exception as e:
return Response({'detail': '%s' % e}, status=400)
car_ser = self.get_serializer(instance=car_query, data=request_data, many=True, partial=True)
car_ser.is_valid(raise_exception=True)
car_list = car_ser.save()
return APIResponse(msg='群局部改成功', results=self.get_serializer(car_list, many=True).data)
def many_destroy(self, request, *args, **kwargs):
try:
rows=self.get_queryset().update(is_delete=True)
except:
return APIResponse(1, '数据有误')
if rows:
return APIResponse(0, '群删成功')
return APIResponse(1, '删除失败')
# 群增与单增必须公用一个接口,都要走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 import serializers
from . import models
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
},
}
标签:自己 直接 python upd view设置 pre require response 映射关系
原文地址:https://www.cnblogs.com/lidandanaa/p/12121973.html