1.分页

2.视图

3.路由

4.渲染器

1.分页

方法一:

from django.shortcuts import render
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import IndexSerializer
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination,CursorPagination
from . import models # Create your views here.
#方法一,有分页,基于limint offset 分页
class P1(LimitOffsetPagination):
default_limit =1#一页默认几个
limit_query_param = 'limit' #关键字后面跟的是一页显示几个
offset_query_param = 'offset'#这个后面跟的是从哪里显示
max_limit = 2 #这个是一页最多显示有几个
#如果把数据放在对象里面,就要变成字典形式即可
class BaseResponse(object):
def __init__(self,code=1000,data=None,error=None):
self.code=code
self.data=data
self.error=error class IndexView(APIView):
def get(self,request,*args,**kwargs):
ret=BaseResponse()
try:
user_list=models.UserInfo.objects.all()#找到所有的数据项
p1 = P1()#实例化分页器,
page_user_list=p1.paginate_queryset(queryset=user_list,request=request,view=self)#把数据放在分页器上面
ser=IndexSerializer(instance=page_user_list,many=True)#序列化数据
ret.data=ser.data
ret.next=p1.get_next_link()
except Exception as e:
ret.code=1001
ret.error='xxxx错误' return Response(ret.__dict__) #对象序列化不了,转成字典形式即可
# return p1.get_paginated_response(ret)#这个会显示上一页和下一页
# return p1.get_paginated_response(ser.data)#这个会显示上
#1.2 普通方法
class IndexView(APIView):
def get(self,request,*args,**kwargs):
user_list=models.UserInfo.objects.all()#找到所有的数据项
p1 = P1()#实例化分页器,
page_user_list=p1.paginate_queryset(queryset=user_list,request=request,view=self)#把数据放在分页器上面
ser=IndexSerializer(instance=page_user_list,many=True)#序列化数据
ret={
'code':111,
'data':ser.data
}
# return Response(ret)#这个不会显示上一页和下一页
# return p1.get_paginated_response(ret)#这个会显示上一页和下一页
return p1.get_paginated_response(ser.data)#这个会显示上一页和下一页

方法二:

方法二:#http://127.0.0.1:8000/app01/v1/user/?page=1&size=2
# class P2(PageNumberPagination):
# #每页显示的数据条数
# page_size =2 #每页显示的多少
# page_size_query_param = 'size'#关键字
# max_page_size = 5 #每页最多显示多少个
# #页码
# page_query_param = 'page'#页码是从1开始的,也是关键字
#
#
# class IndexView(APIView):
# def get(self,request,*args,**kwargs):
# user_list=models.UserInfo.objects.all()#找到所有的数据项
# p1 = P2()#实例化分页器,
# page_user_list=p1.paginate_queryset(queryset=user_list,request=request,view=self)#把数据放在分页器上面
# ser=IndexSerializer(instance=page_user_list,many=True)#序列化数据
# ret={
# 'code':111,
# 'data':ser.data
# }
# # return Response(ret)#这个不会显示上一页和下一页
# # return p1.get_paginated_response(ret)#这个会显示上一页和下一页
# return p1.get_paginated_response(ser.data)#这个会显示上一页和下一页

方法三:

class P3(CursorPagination):
# cursor_query_param = 'cursor'#关键字,c
# page_size =2 #每页默认的数量
# ordering = 'id'#按照id排列
# page_size_query_param ='page_size'#每页显示的数量
#
#
#
# class IndexView(APIView):
# def get(self,request,*args,**kwargs):
# user_list=models.UserInfo.objects.all()#找到所有的数据项
# p1 = P3()#实例化分页器,
# page_user_list=p1.paginate_queryset(queryset=user_list,request=request,view=self)#把数据放在分页器上面
# print('分页数据',page_user_list)
# ser=IndexSerializer(instance=page_user_list,many=True)#序列化数据
# ret={
# 'code':111,
# 'data':ser.data
# }
# # return Response(ret)#这个不会显示上一页和下一页
# # return p1.get_paginated_response(ret)#这个会显示上一页和下一页
# return p1.get_paginated_response(ser.data)#这个会显示上一页和下一页

2.视图

自定义URL:

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^user/$', views.TestView.as_view()),
]
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.pagination import CursorPagination
from rest_framework.serializers import Serializer
from rest_framework import viewsets
from rest_framework.response import Response
from app01.serializer import IndexSerializer
from app01 import models # Create your views here. class TestView(APIView): # serializer_class = IndexSerializer
def get(self,request,*args,**kwargs):
user_list = models.UserInfo.objects.all()
print(user_list)
ser=IndexSerializer(instance=user_list,many=True)
print(type(ser)) return Response([1,2,3])
def retrieve(self,request,*args,**kwargs):
pass
def create(self,request,*args,**kwargs):
pass

方法二:

from django.conf.urls import url

from . import views

urlpatterns = [
url(r'^user/$', views.TestView.as_view({'get': 'list', 'post': 'create'})),
url(r'^user/(?P<pk>\d+)/$',views.TestView.as_view({'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'})),
]
from rest_framework import viewsets
from rest_framework.response import Response
from app01.serializer import IndexSerializer
from app01 import models class TestView(viewsets.GenericViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = IndexSerializer
def list(self,request,*args,**kwargs): return Response('......')
def retrieve(self,request,*args,**kwargs):
pass
def create(self,request,*args,**kwargs):
pass

方式三:

from django.conf.urls import url,include
from rest_framework import routers
from . import views
routers=routers.DefaultRouter()
routers.register(r'user',views.TestView)
urlpatterns=[
url(r'^',include(routers.urls)),
]
from rest_framework.viewsets import  ModelViewSet
from rest_framework import serializers
from app01 import models
from rest_framework import viewsets
class UserSeriallizer(serializers.ModelSerializer):
class Meta:
model=models.UserInfo
fields=('username','password')
class TestView(viewsets.ModelViewSet):
queryset = models.UserInfo.objects.all()
serializer_class = UserSeriallizer

3.路由

有三种情况:

一:普通版

from django.conf.urls import url,include
from rest_framework.routers import DefaultRouter from . import views
urlpatterns = [
url(r'^user/',views.IndexView.as_view()),
url(r'^user\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view()),
url(r'^user/(?P<pk>\d+)/$',views.IndexView.as_view()),
url(r'^user/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view()),
]
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets
from app01 import models
from app01.serializer import IndexSerializer
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer,AdminRenderer
from rest_framework.pagination import PageNumberPagination # Create your views here. class IndexView(APIView):
renderer_classes = [JSONRenderer,AdminRenderer,] def get(self, request, *args, **kwargs):
print(self.renderer_classes)
return Response({'name':'frank'})#Admin必须返回一个键值对形式的值
# return Response('.......') def delete(self, request, *args, **kwargs):
return Response('.....')

二:半自动URl

# urlpatterns = [
#
# url(r'^user/$',views.IndexView.as_view({'get':'list','post':'create'})),
# url(r'^user/\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view({'get':list,'post':'create'})),
# url(r'^user/(?P<pk>\d+)/$',views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
# url(r'^user/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
# ]
class P2(PageNumberPagination):
#每页显示的数据条数
page_size =2 #每页显示的多少
page_size_query_param = 'size'#关键字
max_page_size = 5 #每页最多显示多少个
#页码
page_query_param = 'page'#页码是从1开始的,也是关键字
class IndexView(viewsets.ModelViewSet):
# renderer_classes = [JSONRenderer, BrowsableAPIRenderer]
queryset = models.UserInfo.objects.all()
serializer_class =IndexSerializer
pagination_class = P2
from  rest_framework import serializers
from app01 import models class IndexSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = '__all__'

全自动URL:

from django.conf.urls import url,include
from rest_framework.routers import DefaultRouter from . import views
# urlpatterns = [
# url(r'^user/',views.IndexView.as_view()),
# url(r'^user\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view()),
# url(r'^user/(?P<pk>\d+)/$',views.IndexView.as_view()),
# url(r'^user/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view()),
# ]
#半自动
# urlpatterns = [
#
# url(r'^user/$',views.IndexView.as_view({'get':'list','post':'create'})),
# url(r'^user/\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view({'get':list,'post':'create'})),
# url(r'^user/(?P<pk>\d+)/$',views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
# url(r'^user/(?P<pk>\d+)\.(?P<format>[a-z0-9]+)/$',views.IndexView.as_view({'get':'retrieve','delete':'destroy','put':'update','patch':'partial_update'})),
# ]
router=DefaultRouter()
router.register('index',views.IndexView)
urlpatterns=[
url(r'^',include(router.urls))
]
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import viewsets
from app01 import models
from app01.serializer import IndexSerializer
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer,AdminRenderer
from rest_framework.pagination import PageNumberPagination
#
#
# # Create your views here.
#
# class IndexView(APIView):
# renderer_classes = [JSONRenderer,AdminRenderer,]
#
# def get(self, request, *args, **kwargs):
# print(self.renderer_classes)
# return Response({'name':'frank'})
# # return Response('.......')
#
# def delete(self, request, *args, **kwargs):
# return Response('.....') class P2(PageNumberPagination):
#每页显示的数据条数
page_size =2 #每页显示的多少
page_size_query_param = 'size'#关键字
max_page_size = 5 #每页最多显示多少个
#页码
page_query_param = 'page'#页码是从1开始的,也是关键字
class IndexView(viewsets.ModelViewSet):
# renderer_classes = [JSONRenderer, BrowsableAPIRenderer]
queryset = models.UserInfo.objects.all()
serializer_class =IndexSerializer
pagination_class = P2
from  rest_framework import serializers
from app01 import models # class IndexSerializer(serializers.Serializer):
# # id=serializers.IntegerField()
# # username=serializers.CharField()
# # password=serializers.CharField() class IndexSerializer(serializers.ModelSerializer):
class Meta:
model = models.UserInfo
fields = '__all__'

4.渲染器

看到的页面是什么样子的,返回数据。

renderer_classes = [JSONRenderer,]#返回的是一个json数据格式的没有任何外在的形式

renderer_classes = [BrowsableAPIRenderer,]#返回的带有的页面格式

我们一般使用这两个渲染器

"""demo URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url,include
from django.contrib import admin urlpatterns = [ url(r'^app01/(?P<version>[v1|v2]+)/', include('app01.urls')),
url(r'^app02/(?P<version>[v1|v2]+)/', include('app02.urls')),
url(r'^app03/(?P<version>[v1|v2]+)/', include('app03.urls')),
url(r'^app04/(?P<version>[v1|v2]+)/', include('app04.urls')),
]
from django.conf.urls import url

from  . import views
urlpatterns = [ url(r'^user/',views.IndexView.as_view()),
]
from app01 import models
from app01.serializer import IndexSerializer
from rest_framework.renderers import JSONRenderer, BrowsableAPIRenderer
from rest_framework.views import APIView
from rest_framework.response import Response class IndexView(APIView):
renderer_classes = [JSONRenderer, BrowsableAPIRenderer] def get(self, request, *args, **kwargs):
user_list = models.UserInfo.objects.all()
ser = IndexSerializer(instance=user_list, many=True)
return Response(ser.data)

Django REST framework 之分页,视图,路由,渲染器的更多相关文章

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

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

  2. Django Rest framework 之 分页

    RESTful 规范 django rest framework 之 认证(一) django rest framework 之 权限(二) django rest framework 之 节流(三) ...

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

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

  4. Django REST framework基础:视图和路由

    DRF中的Request 在Django REST Framework中内置的Request类扩展了Django中的Request类,实现了很多方便的功能--如请求数据解析和认证等. 比如,区别于Dj ...

  5. Django REST framework 中的视图

    1.Request REST framework传入视图的request对象不再是Django默认的Httprequest对象,而是DRF提供的扩展类的Request类的对象 常用属性 request ...

  6. django rest framework实现分页功能

    在web开发中很多需求都需要实现分页功能,然而 Django Rest Framework 自带的分页功能,只能在 mixins.ListModelMixin and generics.Generic ...

  7. DRF (Django REST framework) 中的视图类

    视图说明 1. 两个基类 1)APIView rest_framework.views.APIView APIView是REST framework提供的所有视图的基类,继承自Django的View父 ...

  8. Django rest framework 之分页

    Django rest_framework 中分页可分为三类: PageNumberPagination:看第 n 页,每页显示 n 条数据 LimitOffsetPagination:在 n 个位置 ...

  9. Django Rest Framework源码剖析(五)-----解析器

    一.简介 解析器顾名思义就是对请求体进行解析.为什么要有解析器?原因很简单,当后台和前端进行交互的时候数据类型不一定都是表单数据或者json,当然也有其他类型的数据格式,比如xml,所以需要解析这类数 ...

随机推荐

  1. js从一个对象数组中根据属性值大小排序

    <script type="text/javascript"> var sdts = [ {name:"小明",age:30}, {name:&qu ...

  2. 使用flexible适配移动端h5页面

    flexible是淘宝提供的一套REM手机适配的库,用法也非常简单 首先,在页面中引入相关资源 包括flexible.js和flexible_css.js(用于清除默认样式),或者通过cdn方式引入 ...

  3. Deep learning with Python 学习笔记(8)

    Keras 函数式编程 利用 Keras 函数式 API,你可以构建类图(graph-like)模型.在不同的输入之间共享某一层,并且还可以像使用 Python 函数一样使用 Keras 模型.Ker ...

  4. [转]Angular2 使用管道Pipe以及自定义管道格式数据

    本文转自:https://www.pocketdigi.com/20170209/1563.html 管道(Pipe)可以根据开发者的意愿将数据格式化,还可以多个管道串联. 纯管道(Pure Pipe ...

  5. Java的XML解析

    XML:(eXtensible Markup Language) 可扩展标记语言 是一种数据格式,用于存储和传输数据 声明一个xml文件 <?xml version="1.0" ...

  6. CSS设置百分比值的问题

    当给元素设置width:100%:height:100% 的时候没有反应 因为,元素的宽高是根据内容来自动适应的,当设置百分比值时,是根据这个元素的父元素来确定百分比的 如果父元素没有固定的值,那就需 ...

  7. power of the test

    https://www.youtube.com/watch?v=UApFKiK4Hi8

  8. sublime3安装ctags追踪插件

    sublime3经常要用到函数追踪插件,怎做的?下面看安装步骤: 1.安装package control 按快捷键 ctrl+shift+p 2.安装搜索 ctags插件 3.下载ctags可执行程序 ...

  9. canvas-star2.html

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. 【代码笔记】Web-JavaScript-JavaScript语法

    一,效果图. 二,代码. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> ...