分页的实现
@blue.route('/paginate/')
def stu_page():
page = int(request.args.get('page', '1'))
# 1.offset+limit
stus = Students.query.offset((page - 1) * 2).limit(2)
# 2.切片
stus = Students.query.all()[(page - 1) * 2:page * 2]
# 3.sql
sql = 'select * from students limit %s,%s' % ((page - 1) * 2, 2)
stus = db.session.execute(sql)
# paginate()方法
paginate = Students.query.paginate(page, 3)
stus = paginate.items
return render_template('stus.html', stus=stus, paginate=paginate)
前端页面中的展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Students</title>
</head>
<body>
<table>
<thead>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</thead>
<tbody>
{% for stu in stus %}
<tr>
<td>{{ stu.id }}</td>
<td>{{ stu.s_name }}</td>
<td>{{ stu.s_age }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<br>
<p>当前是第{{ paginate.page }}页,总共有{{ paginate.pages }}页</p>
{% if paginate.has_prev %}
<a href="{{ url_for('user.stu_page') }}?page={{ paginate.prev_num }}">上一页</a>
{% endif %}
{% for page in paginate.iter_pages() %}
{% if page %}
{% if page == paginate.page %}
<a href="###">{{ page }}</a>
{% else %}
<a href="{{ url_for('user.stu_page') }}">{{ page}}</a>
{% endif %}
{% else %}
<a href="###">…</a>
{% endif %}
{% endfor %}
{% if paginate.has_next %}
<a href="{{ url_for('user.stu_page') }}?page={{ paginate.next_num }}">下一页</a>
{% endif %}
</body>
</html>
网友评论