簡體   English   中英

Flask SQLAlchemy分頁錯誤

[英]Flask SQLAlchemy pagination error

我有這個代碼和all()方法和所有其他方法的工作,我已經看了一遍,我可以說方法paginate()適用於BaseQuery ,這也是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'我到處尋找,我找不到任何解決方案。

從你的問題......

that the method paginate() works on BaseQuery which is also Query

我認為這是你感到困惑的地方。 “Query”指的是SQLAlchemy Query對象。 “BaseQuery”指的是Flask-SQLALchemy BaseQuery對象,它是Query的子類。 該子類包括諸如first_or_404()paginate()類的幫助器。 但是,這意味着Query對象沒有paginate()函數。 實際構建調用“Query”對象的對象的方式取決於您是在處理Query還是BaseQuery對象。

在此代碼中,您將獲得SQLAlchemy Query對象,從而導致錯誤:

db.session.query(models.Post).paginate(...)

如果您使用以下代碼,則會獲得您正在尋找的分頁,因為您正在處理BaseQuery對象(來自Flask-SQLAlchemy)而不是Query對象(來自SQLAlchemy)。

models.Post.query.paginate(...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM