Cursor Pagination With SQLAlchemy
Implement cursor-based pagination with SQLAlchemy for stable large dataset traversal.
Code
from sqlalchemy import select, asc
from sqlalchemy.ext.asyncio import AsyncSession
async def cursor_paginate(session, model, limit, after_id=None):
stmt = select(model).order_by(asc(model.id)).limit(limit + 1)
if after_id:
stmt = stmt.where(model.id > after_id)
result = await session.execute(stmt)
items = result.scalars().all()
has_next = len(items) > limit
return items[:limit], items[limit].id if has_next else NoneReport a problem with this exampleOpens a pre-filled issue on GitHub.