1. 程式人生 > >django之分頁查詢

django之分頁查詢

.html lac html ive path com lse font port

1.自定義分頁函數

#第一個參數:request對象;第二個參數:需要分頁的數據;第三個參數:每頁顯示的數據個數;第四個參數:需要返回的網頁---->"myadmin/user/index.html"

#導入分頁類

from django.core.paginator import Paginator

def page(r,data,pagenum,path):
# 實例化分頁類
paginator = Paginator(data,pagenum)
# 獲取當前頁碼
p = int(r.GET.get(‘p‘,1))
# 獲取當前頁碼的數據
pagedata = paginator.page(p)

# 獲取總頁碼數
pagecount = paginator.num_pages
# 獲取頁碼範圍,循環
pagerange = paginator.page_range
# 對頁碼進行判斷,防止頁碼小於1或大於最大頁碼數
if p < 1:
p = 1
if p > pagecount:
p = pagecount
# 返回頁碼循環數,在模板裏遍歷
if p <= 5:
page_list = pagerange[:10]
elif p + 5 > pagecount:

page_list = pagerange[-10:]
else:
page_list = pagerange[p-5:p+4]
# 返回分頁後的數據,分頁範圍循環,當前頁碼
return render(r,path,{‘info‘:pagedata,‘page_list‘:page_list,‘p‘:p})
2.視圖函數中 調用函數,傳遞實參

   return page(request,data,20,‘myadmin/user/userlist.html‘)

 3.模板中遍歷數據

<div class="am-u-sm-12">
<table width="100%" class="am-table am-table-compact am-table-striped tpl-table-black " id="example-r">

<thead>
<tr>
<th>id</th>
<th>頭像</th>
<th>用戶名</th>
<th>密碼</th>
<th>手機號碼</th>
<th>年齡</th>
<th>性別</th>
<th>狀態</th>
<th>郵箱</th>
<th>添加時間</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for i in info %}
<tr class="gradeX">
<td>{{ i.id }}</td>
<td><img src="{{ i.pic_url }}" width="50"></td>
<td>{{ i.username }}</td>
<td>******</td>
<td>{{ i.phone }}</td>
<td>{{ i.age }}</td>
<td>
{% if i.sex == ‘0‘ %}女
{% else %}男
{% endif %}
</td>
<td>
{% if i.status == 0 %}正常
{% else %}異常
{% endif %}
</td>
<td>{{ i.email }}</td>
<td>{{ i.addtime }}</td>
<td>
<div class="tpl-table-black-operation">
<a href="{% url ‘admin_useredit‘ i.id %}">
<i class="am-icon-pencil"></i> 編輯
</a>
<a href="{% url ‘admin_userdel‘ i.id %}" class="tpl-table-black-operation-del">
<i class="am-icon-trash"></i> 刪除
</a>
</div>
</td>
</tr>
{% endfor %}
<!-- more data -->
</tbody>
</table>
</div>
<div class="am-u-lg-12 am-cf">
<div class="am-fr">
<ul class="am-pagination tpl-pagination">
<li>
<a href="?p={{p|add:-1}}">?</a>
</li>
{% for i in page_list %}
<li {% if p == i %} class="am-active" {% endif %}>
<a href="?p={{i}}&types={{ request.GET.types }}&keywords={{ request.GET.keywords }}">{{i}}</a>

</li>
{% endfor %}
<li>
<a href="?p={{p|add:1}}">?</a>
</li>
</ul>
</div>
</div>
 

django之分頁查詢