一、rest framework的分页

1、使用rest framework内置类PageNumberPagination实现分类

from django.conf.urls import url
from api import views urlpatterns = [
url(r'^(?P<version>[v1|v2]+)/pager1/$', views.Pager1View.as_view()),
]

urls.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination from api import models
from api.utils.serializers.pager import PagerSerializer class Pager1View(APIView):
"""分页"""
def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
# 使用PageNumberPagination类进行分页
pg = PageNumberPagination()
# 获取分页数据
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
# 序列化分页结果
serl = PagerSerializer(instance=pager_roles, many=True)
return Response(serl.data)

views.py

2、继承内置类自定义分页

from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from api import models
from api.utils.serializers.pager import PagerSerializer class MyPageNumberPagination(PageNumberPagination):
"""自定义分页类"""
page_size = 2 # 设置一页显示2条数据
# page_size_query_param = None # 设置请求参数的key
# 设置为size 可以在请求参数重置每页显示的数据条数
page_size_query_param = "size" # http://127.0.0.1:8082/api/v1/pager1/?size=3
max_page_size = 5 # 设置每页最大显示的数据条数 page_query_param = 'page' # 获取页码 http://127.0.0.1:8082/api/v1/pager1/?page=2 获取第二页数据 class Pager1View(APIView):
"""分页显示"""
def get(self, request, *args, **kwargs): roles = models.Role.objects.all()
pg = MyPageNumberPagination()
# 获取分页数据
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
# 序列化分页结果
serl = PagerSerializer(instance=pager_roles, many=True) # return Response(serl.data) # 还可以使用内置方法返回数据
res = pg.get_paginated_response(serl.data)
return res

views.py

3、LimitOffsetPagination类

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination, LimitOffsetPagination
from api import models
from api.utils.serializers.pager import PagerSerializer class Pager1View(APIView):
"""分页显示"""
def get(self, request, *args, **kwargs): roles = models.Role.objects.all()
pg = LimitOffsetPagination() # 使用的是offset设置索引的ID
# http://127.0.0.1:8082/api/v1/pager1/?offset=2 表示从第3条数据开始显示
# http://127.0.0.1:8082/api/v1/pager1/?offset=2&limit=4 表示从第3条数据开始向后取4条
# 获取分页数据
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
# 序列化分页结果
serl = PagerSerializer(instance=pager_roles, many=True) return Response(serl.data)

views.py

4、CursorPagination类

from rest_framework.views import APIView
from rest_framework.pagination import CursorPagination
from api import models
from api.utils.serializers.pager import PagerSerializer class MyCursorPagination(CursorPagination):
"""自定义分页类"""
cursor_query_param = 'cursor'
page_size = 2
ordering = 'id' # 获取数据时的排序规则
page_size_query_param = None
max_page_size = None class Pager1View(APIView):
"""分页显示"""
def get(self, request, *args, **kwargs): roles = models.Role.objects.all()
pg = MyCursorPagination()
# 获取分页数据
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
# 序列化分页结果
serl = PagerSerializer(instance=pager_roles, many=True) res = pg.get_paginated_response(serl.data)
return res

views.py

二、rest framework的视图

1、APIView

from django.conf.urls import url
from api import views urlpatterns = [
url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view()),
]

urls.py

from rest_framework.views import APIView
from rest_framework.response import Response class ViewerView(APIView):
"""继承APIView"""
def get(self, request, *args, **kwargs):
return Response("xxx")

views.py

2、GenericAPIView

from django.db import models

class UserGroup(models.Model):
title = models.CharField(max_length=32) class UserInfo(models.Model):
user_type_choices = (
(1, "普通用户"),
(2, "vip"),
(3, "svip"),
)
user_type = models.IntegerField(choices=user_type_choices)
username = models.CharField(max_length=32, unique=True)
password = models.CharField(max_length=64)
group = models.ForeignKey(to="UserGroup", on_delete=models.CASCADE, null=True, blank=True)
roles = models.ManyToManyField(to="Role", blank=True) class UserToken(models.Model):
user = models.OneToOneField(to="UserInfo")
token = models.CharField(max_length=64) class Role(models.Model):
title = models.CharField(max_length=32) class Order(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
create_time = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(to="UserInfo", on_delete=models.CASCADE, null=True, blank=True)

models.py

from django.conf.urls import url
from api import views urlpatterns = [
url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view()),
]

urls.py

from rest_framework import serializers
from api import models class ViewSerializer(serializers.ModelSerializer):
class Meta:
model = models.Role
fields = "__all__"

view_serializer.py

from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination from api import models
from api.utils.serializers.view_serializer import ViewSerializer class ViewerView(GenericAPIView):
"""继承GenericAPIView"""
queryset = models.Role.objects.all() # 指定要查询的数据
serializer_class = ViewSerializer # 序列化类
pagination_class = PageNumberPagination # 分页类 def get(self, request, *args, **kwargs):
roles = self.get_queryset() # 获取数据
pager = self.paginate_queryset(roles) # 分页
serl = self.get_serializer(instance=pager, many=True) # 序列化
return Response(serl.data)

views.py

3、GenericViewSet

继承了ViewSetMixin和GenericAPIView

from django.conf.urls import url
from api import views urlpatterns = [
url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view({'get': 'list'})),
]

urls.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination from api import models
from api.utils.serializers.view_serializer import ViewSerializer class ViewerView(GenericViewSet):
"""继承GenericViewSet"""
queryset = models.Role.objects.all() # 指定要查询的数据
serializer_class = ViewSerializer # 序列化类
pagination_class = PageNumberPagination # 分页类 def list(self, request, *args, **kwargs):
roles = self.get_queryset() # 获取数据
pager = self.paginate_queryset(roles) # 分页
serl = self.get_serializer(instance=pager, many=True) # 序列化
return Response(serl.data)

views.py

4、ListModelMixin、CreateModelMixin、GenericViewSet

ListModelMixin内部实现了list方法:

CreateModelMixin内部实现了create方法:

from django.conf.urls import url
from api import views urlpatterns = [
url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view({'get': 'list', 'post': 'create'})),
]

urls.py

from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.pagination import PageNumberPagination from api import models
from api.utils.serializers.view_serializer import ViewSerializer class ViewerView(ListModelMixin, CreateModelMixin, GenericViewSet):
"""继承ListModelMixin、CreateModelMixin、GenericViewSet"""
queryset = models.Role.objects.all() # 指定要查询的数据
serializer_class = ViewSerializer # 序列化类
pagination_class = PageNumberPagination # 分页类

views.py

5、ModelViewSet

获取单条数据、更新数据、删除数据时,URL中需要传递要操作的数据的ID

from django.conf.urls import url
from api import views urlpatterns = [
url(r'^(?P<version>[v1|2]+)/viewer/(?P<pk>\d+)$', views.ViewerView.as_view({'get': 'retrieve',
'post': 'create',
'delete': 'destroy',
'put': 'update',
'patch': 'partial_update'})),
]

urls.py

from rest_framework.viewsets import ModelViewSet
from rest_framework.pagination import PageNumberPagination from api import models
from api.utils.serializers.view_serializer import ViewSerializer class ViewerView(ModelViewSet):
"""继承ModelViewSet"""
queryset = models.Role.objects.all() # 指定要查询的数据
serializer_class = ViewSerializer # 序列化类
pagination_class = PageNumberPagination # 分页类

views.py

6、当使用GenericViewSet类时,会执行它父类GenericAPIView里面的get_object方法,这个方法执行了check_object_permissions方法来对对象的权限进行校验:

三、rest framework的路由

url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view())
# http://127.0.0.1:8080/api/v2/viewer/ url(r'^(?P<version>[v1|2]+)/viewer/$', views.ViewerView.as_view({'get': 'list', 'post': 'create'}))
# http://127.0.0.1:8080/api/v2/viewer/
# http://127.0.0.1:8080/api/v2/viewer/?format=json get传参的方式 url(r'^(?P<version>[v1|2]+)/viewer\.(?P<format>\w+)$', views.ViewerView.as_view({'get': 'list', 'post': 'create'}))
# http://127.0.0.1:8080/api/v2/viewer.json 将参数写到路径里面

自动生成路由:

from django.conf.urls import url, include
from rest_framework import routers
from api import views router = routers.DefaultRouter()
router.register(r"role", views.ViewerView) # url前缀,视图名称
router.register(r"group", views.ViewerView) urlpatterns = [
url(r'^(?P<version>[v1|2]+)/', include(router.urls)),
]

urls.py

自动生成的路由:

可以通过http://127.0.0.1:8080/api/v2/role/    http://127.0.0.1:8080/api/v2/role.json等方式进行访问

四、rest framework的渲染器

1、局部配置

urlpatterns = [
url(r'^(?P<version>[v1|2]+)/test/$', views.TestView.as_view()),
]

urls.py

from rest_framework import serializers
from api import models class ViewSerializer(serializers.ModelSerializer):
class Meta:
model = models.Role
fields = "__all__"

view_serializer.py

from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer, AdminRenderer from api import models
from api.utils.serializers.view_serializer import ViewSerializer class TestView(APIView):
renderer_classes = [JSONRenderer, BrowsableAPIRenderer] # 渲染数据格式的类 http://127.0.0.1:8080/api/v2/test/?format=json
# renderer_classes = [AdminRenderer, BrowsableAPIRenderer] # 渲染数据格式的类 http://127.0.0.1:8080/api/v2/test/?format=admin def get(self, request, *args, **kwargs):
roles = models.Role.objects.all()
pg = PageNumberPagination()
pager_roles = pg.paginate_queryset(queryset=roles, request=request, view=self)
serl = ViewSerializer(instance=pager_roles, many=True)
return Response(serl.data)

views.py

2、全局配置

在项目的settings里面:

django的rest framework框架——分页、视图、路由、渲染器的更多相关文章

  1. Django-RestFrameWork之分页 视图 路由 渲染器

    目录 一.分页 二.视图 三.路由 四.渲染器 一.分页 试问如果当数据量特别大的时候,你是怎么解决分页的? 方式a.记录当前访问页数的数据id 方式b.最多显示120页等 方式c.只显示上一页,下一 ...

  2. 基于Django的Rest Framework框架的视图组件

    本文目录 一 基本视图 二 mixin类和generice类编写视图 三 使用generics 下ListCreateAPIView,RetrieveUpdateDestroyAPIView 四 使用 ...

  3. Django之Rest Framework框架

    一.什么是RESTful REST与技术无关,代表的是一种软件架构风格,REST是Representational State Transfer的简称,中文翻译为“表征状态转移” REST从资源的角度 ...

  4. Django rest framework(8)---- 视图和渲染器

    django rest framework 之视图 序列化器    PagerSerialiser from rest_framework import serializers from api im ...

  5. django的rest framework框架——安装及基本使用

    一.django的FBV 和 CBV 1.FBV(基于函数的视图): urlpatterns = [ url(r'^users/', views.users), ] def users(request ...

  6. 基于Django的Rest Framework框架的url控制器

    本文目录 一 自定义路由(原始方式) 二 半自动路由(视图类继承ModelViewSet) 三 全自动路由(自动生成路由) 回到目录 一 自定义路由(原始方式) from django.conf.ur ...

  7. Django:(05)类视图,装饰器和中间件

    一.类视图的定义和使用 在Django中还可以通过类来定义一个视图,称为类视图. 定义一个类视图:定义一个类,需继承 Django 提供的 View 类 . from django.views.gen ...

  8. 基于Django的Rest Framework框架的分页组件

    本文目录 一 简单分页(查看第n页,每页显示n条) 二 偏移分页(在第n个位置,向后查看n条数据) 三 CursorPagination(加密分页,只能看上一页和下一页,速度快) 回到目录 一 简单分 ...

  9. django的rest framework框架——版本、解析器、序列化

    一.rest framework的版本使用 1.版本可以写在URL中,通过GET传参,如 http://127.0.0.1:8082/api/users/?version=v1 (1)自定义类获取版本 ...

随机推荐

  1. “玲珑杯”ACM比赛 Round #4 E -- array DP

    http://www.ifrog.cc/acm/problem/1050?contest=1006&no=4 DP[val]表示以val这个值结尾的等差数列有多少个 DP[val] += DP ...

  2. Memcached 未授权访问漏洞及加固

    memcached是一套分布式的高速缓存系统.它以Key-Value(键值对)形式将数据存储在内存中,这些数据通常是应用读取频繁的.正因为内存中数据的读取远远大于硬盘,因此可以用来加速应用的访问. 漏 ...

  3. 按位&按位|按位~的详解

    十进制转二进制: 例:十进制(5)---->二进制(00000101) 将整数除二取余,继续用除二的结果除二取余,最后将结果从下往上连接起来,不足八位,前面填0 二进制转十进制 例:二进制(00 ...

  4. kafka安装和使用

    kafka安装和启动 kafka的背景知识已经讲了很多了,让我们现在开始实践吧,假设你现在没有Kafka和ZooKeeper环境. Step 1: 下载代码 下载0.10.0.0版本并且解压它. &g ...

  5. sql中保留2位小数

    问题: 数据库里的 float momey 类型,都会精确到多位小数.但有时候 我们不需要那么精确,例如,只精确到两位有效数字. 解决: 1. 使用 Round() 函数,如 Round(@num,2 ...

  6. 百度影棒安装apk方法

    确保影棒和电脑接入家中同一WIFI中,开启影棒USB调试,手机端运行悟空助手或沙发管家等软件,之后无线推送需要安装的APK. 安装文件管理apk后,可以使用U盘安装.

  7. Ambiguous mapping. Cannot map 'registerController' method

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'requestMappi ...

  8. UVA - 1658 Admiral (最小费用最大流)

    最短路对应费用,路径数量对应流量.为限制点经过次数,拆点为边.跑一次流量为2的最小费用最大流. 最小费用最大流和最大流EK算法是十分相似的,只是把找增广路的部分换成了求费用的最短路. #include ...

  9. elasticsearch最全详细使用教程:搜索详解

    一.搜索API 1. 搜索API 端点地址从索引tweet里面搜索字段user为kimchy的记录 GET /twitter/_search?q=user:kimchy从索引tweet,user里面搜 ...

  10. (五)使用Docker镜像(上)

    1. 获取镜像 # 获取镜像 docker pull image:tag // 不使用tag 默认下载latest标签的镜像,即最新的镜像. 2. 查看镜像信息 # 查看镜像信息docker imag ...