我正在尝试为商品页面设置分页,就像这样
from flask_paginate import Pagination, get_page_parameter
...
page = request.args.get(get_page_parameter(), type=int, default=1)
per_page = 4
offset = (page) * 10
search = False
q = request.args.get('q')
if q:
search = True
pagination = Pagination(page=page, per_page=per_page, offset=offset, total=len(products),
search=search, record_name='products')
return render_template('products.html', form=form, products=products,
subcategories=subcategories, pagination=pagination)
从代码中的上一个请求中提取“产品”时
cur.execute("SELECT * FROM products")
products = cur.fetchall()
但是,在我的产品页面上,我正在取回数据库中的所有产品(当前为20),同时我看到{{ pagination.info }}
显示“总共显示1-4个产品”。
{{ pagination.links }}
也正常工作,因为它显示了功能的分页链接,但所有产品仍在页面上可见。您有什么解决办法的提示吗?
谢谢
答案 0 :(得分:0)
我找到了解决方案。可能不是最好的方法,如果您知道更好的方法,请告诉我。现在,我已经通过以下方式解决了这个问题:
# Creating a cursor
cur = conn.cursor()
# Setting page, limit and offset variables
per_page = 4
page = request.args.get(get_page_parameter(), type=int, default=1)
offset = (page - 1) * per_page
# Executing a query to get the total number of products
cur.execute("SELECT * FROM products")
total = cur.fetchall()
# Executing a query with LIMIT and OFFSET provided by the variables above
cur.execute("SELECT * FROM products ORDER BY added_on DESC LIMIT %s OFFSET %s", (per_page, offset))
products = cur.fetchall()
# Closing cursor
cur.close()
...
# Setting up the pagination variable, where you are using len(total) to set the total number of
# items available
pagination = Pagination(page=page, per_page=per_page, offset=offset, total=len(total),
record_name='products')
# Render template, where you pass "products" variable
# for the prepared query with LIMIT and OFFSET, and passing "pagination" variable as well.
return render_template('products.html', form=form, products=products, pagination=pagination)