美文网首页
Vue Django Restful framework 前后端

Vue Django Restful framework 前后端

作者: AllenBigBear | 来源:发表于2020-06-25 12:49 被阅读0次

除了上一篇里面说的APIVIEW之外,我们还可以有通用视图的方式来完成数据的读取。

1.Generic View

from .serializer import GoodsSerializer
from rest_framework.response import Response
from rest_framework import status,mixins,generics
from .models import Goods
# Create your views here.

class GoodsListView(generics.ListAPIView):
    '''
    List all , or create a new
    '''

    queryset = Goods.objects.all()[:10]
    serializer_class = GoodsSerializer
效果图

2. 分页功能

现在看到的数据是一页上返回了所有的数据,那如何来做分页呢?
DRF有内置的pagination

首先,需要在项目的settings文件里面对pagination进行配置

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE':10,
}

然后,为了测试用,我们把query_set取消只切割10个,而是获取所有

queryset = Goods.objects.all()

刷新页面,就可以看到已经自动分页了
我们可以看到分页的同时,返回的数据也变了,他同时还返回了该数据的数据总量,下一页的url,前一页的url

自动分页

3. 分页自定义

如果需要用到分页自定义的功能
那么我们就要在views里面引入相关设定

from rest_framework.pagination import PageNumberPagination
# Create your views here.

class StandardResultsSetPagination(PageNumberPagination):
    page_size = 10              #每页显示数据数量
    page_size_query_param = 'page_size'
    page_query_param = 'p'      #URL里面查询参数的名字,可以自定义
    max_page_size = 100         #最大每页显示数据量[图片上传中...(屏幕快照 2020-06-25 12.46.44.png-2c6904-1593060484934-0)]



class GoodsListView(generics.ListAPIView):
    '''
    List all , or create a new
    '''

    queryset = Goods.objects.all()
    serializer_class = GoodsSerializer
    pagination_class = StandardResultsSetPagination
可自定义查询参数

我们注意到,你可以在前端自定义查询每页显示数据,同时,你的查询参数也变成了自定义的‘p’

相关文章

网友评论

      本文标题:Vue Django Restful framework 前后端

      本文链接:https://www.haomeiwen.com/subject/ophsnhtx.html