DRF分頁
一、序列化
from rest_framework import serializers
from .models import *
class GoodsSerializer(serializers.ModelSerializer):
"""
商品序列化
"""
class Meta:
model = Goods
fields = '__all__'
二、views.py檢視
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from .serializer import GoodsSerializer
from django.core.paginator import Paginator, EmptyPage, InvalidPage
class GoodsPageApi(APIView):
"""
分頁
"""
def get(self, request, pindex):
goods_list = Goods.objects.all()
paginat = Paginator(goods_list, 2)
paged = paginat.page(pindex)
try:
paged.has_next()
down_page = paged.next_page_number()
except EmptyPage:
down_page = paged.paginator.num_pages
paged = paginat.page(down_page)
try:
paged.has_previous()
up_page = paged.previous_page_number()
except InvalidPage:
up_page = 1
paged = paginat.page(up_page)
page_serializer = GoodsSerializer(paged, many=True)
return Response({
'code': 200,
'data': page_serializer.data,
'page_list': [i for i in paginat.page_range],
'has_previous': paged.has_previous(),
'has_next': paged.has_next(),
'previous_page_number': up_page,
'next_page_number': down_page,
'page_number': paged.number
})
三、urls.py
path('goods_page/<pindex>', views.GoodsPageApi.as_view()),
四、vue分頁展示
<template>
<div>
<table>
<tr>
<td>商品編碼</td>
<td>商品名稱</td>
<td>商品圖片</td>
<td>商品詳情</td>
<td>商品價格</td>
</tr>
<tr v-for="goods in goods_list">
<td>{{goods.id}}</td>
<td>{{goods.goods_name}}</td>
<td><img :src="'http://127.0.0.1:8000' + goods.goods_img" alt="" style="width:100px; heigth:100px"></td>
<td>{{goods.goods_content}}</td>
<td>{{goods.goods_price}}</td>
</tr>
</table>
<div>
<button v-for="page in page_list" @click="get_num($event)" :value="page">{{page}}</button>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
goods_list: [],
page_list: [],
p: '1'
}
},
methods:{
get_goods(){
var self = this
axios({
method: 'get',
url: 'http://127.0.0.1:8000/myapp/goods_page/'+ this.p
}).then(function(res){
console.log(res.data)
self.goods_list = res.data.data
self.page_list = res.data.page_list
})
},
get_num(event){
this.p = event.target.value // 通過事件獲取button的value
console.log(this.p)
this.get_goods() // 點選按鈕的時候,重新呼叫get_goods方法
}
},
created(){ // 頁面載入的時候,自動執行下面方法
this.get_goods()
}
}
</script>