SQLAlchemy Flask pagination error

I have this code and the all() method, and every other method works on it, and I looked through all its contents, and I could have the paginate() method work on BaseQuery , which was 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) 

but this gives me an AttributeError: 'Query' object has no attribute 'paginate' error AttributeError: 'Query' object has no attribute 'paginate' I searched everywhere and I can not find a solution.

+6
source share
1 answer

From your question ...

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

I think they confuse you here. "Query" refers to an SQLAlchemy Query object. "BaseQuery" refers to the Flask-SQLALchemy BaseQuery , which is a subclass of Query . This subclass includes helpers such as first_or_404() and paginate() . However, this means that the Query object does NOT have a paginate() function. How you actually create the object that you call for the Query object depends on whether you are dealing with a Query or BaseQuery .

In this code, you get an SQLAlchemy Query object, which results in an error:

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

If you use the following code, you get the pagination you are looking for because you are dealing with a BaseQuery object (from Flask-SQLAlchemy), not a Query object (from SQLAlchemy).

 models.Post.query.paginate(...) 
+18
source

Source: https://habr.com/ru/post/952599/


All Articles