flask - 分页

利用paginate 对象:


  • views.py处理分页的业务逻辑

    @stu.route('/stupage/')
    def stu_page():
        # page定义当前页码
        page = int(request.args.get('page',1))
        # per_page定义每页显示的条数
        per_page = int(request.args.get('per_page', 10))
        # 是个对象paginate:<flask_sqlalchemy.Pagination object>
        paginate = Student.query.order_by('-s_id').paginate(page, per_page, error_out=False)
        # 必要步骤
        paginate = Student.query.order_by('-s_id').paginate(page, per_page, error_out=False)
        # 获取全部学生对象
        stus = paginate.items  
        return render_template('stupage.html',paginate=paginate, stus=stus)
    
  • templates中相关操作:

    {% for stu in stus %}
    学生id:{{stus.s_id}}
    学生姓名:{{stus.s_name}}
    学生年龄:{{stu.s_age}}
    <br>
    {% endfor %}    
    
    总共把表格中的记录分了几页{{paginate.pages}}
    当前页码{{paginate.page}}  这个是上面传入的
    表格中总共多少条记录{{paginate.total}}
    
    上一页的页码{{paginate.prev_num}}
    下一页的页码{{paginate.next_num}}
    if has_prev
    if has_next
    
    循环出页码:
    
        {% for i in paginate.iter_pages() %}
            {{i}}
    
        {% endfor %}
    
  • 给request请求传入参数的方式。利用request.args.get(‘page’, 1(自定义找不到默认值))

    <a href='/stu/stupage/?page={{paginate.prev_num}}'>上一页:{{paginate.prev_num}}
    </a>
    

猜你喜欢

转载自blog.csdn.net/hello_syt_2018/article/details/80357031