标签:frame bsp 重写 imp 自定义 time res int framework
最近因为在做分页时遇到的问题很多,页浪费了好多时间,所以记录一下。以后如遇到可用省去不必要的麻烦
restframwork中的官方文档对分页和搜索页进行了详细的介绍,但是我公司需要的return的json数据格式进行分层。所以吧,一个很简单的东西,搞的头皮发嘛,看源码之类的,费时,重点是看不太懂,但最后还是参考源码,重写了response方法。
直接上代码了
url(r‘^show_workPublished‘,views.Show_workPublishedView.as_view(),name=‘show_workPublished‘),
serializer.py
class Show_workPublishedModelSerialiazer(serializers.ModelSerializer): class Meta: model = Upload_filep #fields = ("id","name","title","img") fields = ["id","name","title","img",‘address‘,‘add_time‘]
自定义分页pagination.py
from rest_framework.pagination import PageNumberPagination class PNPageination(PageNumberPagination): page_size = 6 # 每页显示2条 page_query_param = ‘currentPage‘ # 当前页 page_size_query_param = ‘page_size‘ # 每页显示
view.py
class Show_workPublishedView(generics.ListAPIView): queryset = Upload_filep.objects.all().order_by(‘id‘).reverse() pagination_class = PNPageination serializer_class = Show_workPublishedModelSerialiazer #模糊搜索 def get_queryset(self): name = self.request.GET.get(‘keyword‘) if name is not None: return self.queryset.filter(Q(name__icontains=name) | Q(title__icontains=name)) return self.queryset def get(self,request,*args,**kwargs): list = self.get_queryset() #list = Upload_filep.objects.all() list_nums = list.count() try: page = request.GET.get(‘currentPage‘,1) except PageNotAnInteger: page = 1 limit = int(request.GET.get(‘limit‘,6)) p = Paginator(list,limit) lists = p.page(page) #lists_serializer = Show_workPublishedModelSerialiazer(lists,many=True) lists_serializer = self.get_serializer(lists,many=True) ret = { "result": True, "msg": "successful", "secure": False, "returnCode": "200", "data": { "list":{ "listData":lists_serializer.data, "page_size":limit, #每页显示两个 "totalCount":list_nums , # 一共有多少数据 "totalPage": (list_nums//limit if list_nums%limit==0 else list_nums//limit+1) , # 一共有多少页 a-b if a>b else a+b "currentPage": page , # 当前页数 }, }, } return Response(ret)
到这里就能搞定分页和搜索。restframwork分装的比较多,但有的东西还是得参考源码重写方法。
Django restframwork实现自定义数据格式的分页与搜索
标签:frame bsp 重写 imp 自定义 time res int framework
原文地址:https://www.cnblogs.com/shaojiafeng/p/9681652.html