【问题标题】:Flask-paginate is showing all results on one pageFlask-paginate 在一页上显示所有结果
【发布时间】:2019-03-26 21:25:39
【问题描述】:

我正在尝试为产品页面设置分页,像这样

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 个产品 20”。

同样{{ pagination.links }} 工作正常,因为它显示了功能性分页链接,但所有产品仍然在页面上可见。你有什么提示可以解决这个问题吗?

谢谢

【问题讨论】:

  • 没有ORDER BY 的分页没有意义。
  • 感谢您的提示。一旦找到解决方案,我就会记住这一点。

标签: python mysql sql flask pagination


【解决方案1】:

我找到了解决这个问题的方法。也许不是最好的,如果你知道更好的方法,请告诉我。目前,我已经通过以下方式解决了这个问题:

# 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)

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2019-12-05
    • 2016-08-18
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-07
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多