Flask SQLAlchemy 分页错误 [英] Flask SQLAlchemy pagination error
问题描述
我有这个代码和 all()
方法和其他所有方法都适用于此,我已经查看了所有内容,我可以发现 pagination()
方法有效BaseQuery
也是 Query
I have this code and the all()
method and every other method works on this and I have looked all over and I could that the method paginate()
works on BaseQuery
which is also Query
@app.route('/')
@app.route('/index')
@app.route('/blog')
@app.route('/index/<int:page>')
def index(page = 1):
posts = db.session.query(models.Post).paginate(page, RESULTS_PER_PAGE, False)
return render_template('index.html', title="Home", posts=posts)
但这给了我错误 AttributeError: 'Query' object has no attribute 'paginate'
我到处找,但找不到任何解决方案.
but this gives me the error AttributeError: 'Query' object has no attribute 'paginate'
I've looked everywhere and I can't find any solution to this.
推荐答案
来自你的问题...
that the method paginate() works on BaseQuery which is also Query
我认为这是您感到困惑的地方.查询"指的是 SQLAlchemy Query代码>
对象.BaseQuery"指的是 Flask-SQLALchemy BaseQuery
对象,它是Query
的子类.这个子类包括诸如 first_or_404()
和 paginate()
.然而,这意味着 Query
对象没有 paginate()
函数.您实际如何构建您称为查询"对象的对象取决于您是在处理 Query
还是 BaseQuery
对象.
I think this is where you're being confused. "Query" refers to the SQLAlchemy Query
object. "BaseQuery" refers to the Flask-SQLALchemy BaseQuery
object, which is a subclass of Query
. This subclass includes helpers such as first_or_404()
and paginate()
. However, this means that a Query
object does NOT have the paginate()
function. How you actually build the object you are calling your "Query" object depends on whether you are dealing with a Query
or BaseQuery
object.
在这段代码中,你得到了 SQLAlchemy Query
对象,这导致了一个错误:
In this code, you are getting the SQLAlchemy Query
object, which results in an error:
db.session.query(models.Post).paginate(...)
如果你使用下面的代码,你会得到你正在寻找的分页,因为你正在处理一个 BaseQuery
对象(来自 Flask-SQLAlchemy)而不是一个 Query代码> 对象(来自 SQLAlchemy).
If you use the following code, you get the pagination you're looking for, because you are dealing with a BaseQuery
object (from Flask-SQLAlchemy) rather than a Query
object (from SQLAlchemy).
models.Post.query.paginate(...)
这篇关于Flask SQLAlchemy 分页错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!