feat: 增加分页功能

This commit is contained in:
2026-09-08 22:49:44 +08:00
parent a81ff36f21
commit 94b0187268
3 changed files with 49 additions and 4 deletions

View File

@@ -1,8 +1,8 @@
from sqlalchemy import select, desc
from sqlalchemy import select, desc, func
from sqlalchemy.orm import Session, selectinload
from models.family import Records, Comments
from schemas.record import RecordCreate, RecordUpdate, RecordResponse
from schemas.record import RecordCreate, RecordUpdate, RecordResponse, RecordPageResponse
def get_all_records(db: Session, skip: int = 0, limit: int = 20) -> list[RecordResponse]:
@@ -20,6 +20,34 @@ def get_all_records(db: Session, skip: int = 0, limit: int = 20) -> list[RecordR
return [RecordResponse.model_validate(r) for r in records]
def get_all_records_by_page(db: Session, page: int = 1, size: int = 20) -> RecordPageResponse:
base_query = select(Records).options(
selectinload(Records.user),
selectinload(Records.comments).selectinload(Comments.user),
)
# 总数
total = db.scalar(
select(func.count()).select_from(base_query.subquery())
)
# 分页数据
records = db.execute(
base_query
.order_by(Records.create_time.desc())
.offset((page - 1) * size)
.limit(size)
).scalars().all()
return RecordPageResponse(
records=[RecordResponse.model_validate(r) for r in records],
total=total,
page=page,
size=size,
pages=(total + size - 1) // size,
)
def create_record(db: Session, record_dto: RecordCreate) -> bool:
data = record_dto.model_dump()
record = Records(**data)