[파이썬] SQLAlchemy Pagination 기법

When working with large datasets in SQLAlchemy, it is often necessary to display the data in a paginated manner for better user experience. SQLAlchemy provides a convenient way to implement pagination in Python.

Setting up SQLAlchemy

Before diving into the pagination techniques, make sure you have SQLAlchemy installed. You can install it using pip:

pip install SQLAlchemy

Next, import the necessary modules to start using SQLAlchemy:

from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import sessionmaker

Initialize the database connection and create a session:

# configure the database connection
engine = create_engine('sqlite:///data.db', echo=True)

# create a session
Session = sessionmaker(bind=engine)
session = Session()

Implementing Pagination

To implement pagination in SQLAlchemy, you need to use the limit() and offset() methods provided by the query object. The limit() method limits the number of rows returned, while the offset() method skips the specified number of rows.

Here’s an example of how to paginate the results using SQLAlchemy:

# define the table to query
table = Table('users', metadata, autoload=True, autoload_with=engine)

# fetch paginated results
page_number = 1
page_size = 10

query = session.query(table)
total_count = query.count()

# calculate the offset based on the page number and size
offset = (page_number - 1) * page_size

# apply pagination to the query
query = query.limit(page_size).offset(offset)

results = query.all()

In the above example, we are fetching users from the “users” table with a limit of 10 rows per page. We specify the page number and page size to calculate the offset. Finally, we apply the pagination to the query and fetch the paginated results.

To provide a better user experience, it is essential to display pagination links to navigate between pages. You can calculate the total number of pages based on the total count and page size. Then, generate links to different pages dynamically.

Here’s an example of how to display pagination links using Python:

total_pages = (total_count + page_size - 1) // page_size

pagination_links = []
for page in range(1, total_pages + 1):
    link = f"<a href='/users?page={page}'>{page}</a>"
    if page == page_number:
        link = f"<strong>{link}</strong>"
    pagination_links.append(link)

# display the pagination links
pagination_html = ' '.join(pagination_links)
print(pagination_html)

In the above example, we calculate the total number of pages by dividing the total count by the page size. Then, we generate links for each page using a loop. We highlight the current page using strong tags. Finally, we join the links together using spaces and display the pagination links.

Implementing pagination in SQLAlchemy allows you to efficiently manage and display large datasets in a user-friendly manner. By using the limit() and offset() methods, you can fetch and display paginated results. Additionally, displaying pagination links enhances the user experience by enabling easy navigation between pages.