feat:初始化工程
This commit is contained in:
27
schemas/paginate_query.py
Normal file
27
schemas/paginate_query.py
Normal file
@@ -0,0 +1,27 @@
|
||||
from sqlalchemy import select, func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from schemas.pagination import PageResult
|
||||
|
||||
|
||||
def paginate_query(db: Session, query, current_page: int = 1, page_size: int = 10) -> PageResult:
|
||||
"""通用分页查询函数"""
|
||||
# 计算总记录数
|
||||
total = db.execute(select(func.count()).select_from(query.subquery())).scalar_one_or_none() or 0
|
||||
|
||||
# 计算总页数
|
||||
total_pages = (total + page_size - 1) // page_size if page_size != 0 else 0
|
||||
|
||||
# 执行分页查询
|
||||
results = db.execute(query.offset((current_page - 1) * page_size).limit(page_size)).all()
|
||||
|
||||
# 转换为字典列表
|
||||
records = [row._asdict() if hasattr(row, "_asdict") else dict(row) for row in results]
|
||||
|
||||
return PageResult(
|
||||
current=current_page,
|
||||
size=page_size,
|
||||
total=total,
|
||||
pages=total_pages,
|
||||
records=records
|
||||
)
|
||||
Reference in New Issue
Block a user