Django restframwork实现自定义数据格式的分页与搜索
生活随笔
收集整理的這篇文章主要介紹了
Django restframwork实现自定义数据格式的分页与搜索
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近因為在做分頁時遇到的問題很多,頁浪費了好多時間,所以記錄一下。以后如遇到可用省去不必要的麻煩
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 PageNumberPaginationclass 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 = PNPageinationserializer_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.querysetdef 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 = 1limit = 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) View Code?
到這里就能搞定分頁和搜索。restframwork分裝的比較多,但有的東西還是得參考源碼重寫方法。
轉載于:https://www.cnblogs.com/shaojiafeng/p/9681652.html
總結
以上是生活随笔為你收集整理的Django restframwork实现自定义数据格式的分页与搜索的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 积跬步,聚小流-------一个登录中的
- 下一篇: Linux HOOK