python

Implement pagination in Flask-SQLAlchemy

To implement pagination in Flask-SQLAlchemy the .paginate() method can be used. You can pass the page, how many records you want to fetch, etc.

employees = EmployeeModel\
            .query\
            .order_by(EmployeeModel.id.desc())\
            .paginate(
                page=1,
                per_page=10,
                max_per_page=10,
                error_out=False
            )

result = {
    "total_records": employees.total,
    "page": employees.page,
    "items": employees.items
}

You can pass parameters in the .paginate() method. The description is as below:

page

You can pass the page numberr that you want to fetch from the table.

per_page

You can pass the number of records in this parameeter that you want to fetch using the .paginate() method. The default reccords per page are 10 to 20.

max_per_page

In this parameter you can pass the maximum number of records that can be fetched per page.

The paginate object

After running the flask-sqlalchemy query with paginate method you will get the paginate object that will contains total number of records, page number and items.

Was this helpful?