キーワード検索とページネーション
この章では、SQLAlchemyを使って複合検索を実装し、offset/limitでページネーションを実装する方法を学びます。
ilike 大文字小文字を区別しない検索
例
# 単一フィールド検索
posts = db.query(Post).filter(Post.title.ilike(f'%{keyword}%')).all()
# 複数フィールドの複合検索(OR関係)
from sqlalchemy import or_
posts = db.query(Post).filter(
or_(
Post.title.ilike(f'%{keyword}%'),
Post.summary.ilike(f'%{keyword}%')
)
).all()
posts = db.query(Post).filter(Post.title.ilike(f'%{keyword}%')).all()
# 複数フィールドの複合検索(OR関係)
from sqlalchemy import or_
posts = db.query(Post).filter(
or_(
Post.title.ilike(f'%{keyword}%'),
Post.summary.ilike(f'%{keyword}%')
)
).all()
offset/limit ページネーション
Flask-SQLAlchemy は便利な.paginate()メソッドを提供しています。
FastAPI はネイティブ SQLAlchemy を使用しているため、offset + limit手動でページネーションを実装する必要があります。
| ページネーション方式 | Flask-SQLAlchemy | FastAPI(ネイティブ SQLAlchemy) |
|---|---|---|
| 現在のページのデータを取得 | .paginate(page, per_page).items | .offset(skip).limit(per_page).all() |
| 総レコード数 | pagination.total | query.count() |
| 総ページ数 | pagination.pages | 手動計算 math.ceil(total / per_page) |
ページネーション計算式
例
import math
from fastapi import Query
def get_pagination(page: int = 1, size: int = 6):
"""
ページネーションパラメータの計算
page:現在のページ番号(1から始まる)
size:1ページあたりの件数
"""
skip = (page - 1) * size # スキップするレコード数
return skip, size
# 使用例
skip, limit = get_pagination(page=2, size=6)
# skip = 6, limit = 6 → 最初の6件をスキップし、7〜12件目を取得
from fastapi import Query
def get_pagination(page: int = 1, size: int = 6):
"""
ページネーションパラメータの計算
page:現在のページ番号(1から始まる)
size:1ページあたりの件数
"""
skip = (page - 1) * size # スキップするレコード数
return skip, size
# 使用例
skip, limit = get_pagination(page=2, size=6)
# skip = 6, limit = 6 → 最初の6件をスキップし、7〜12件目を取得
完全な検索 + ページネーションビュー
例
# ファイルパス: routers/posts.py(index ルートを拡張)
from sqlalchemy import or_
from math import ceil
from fastapi import APIRouter, Depends, Request, Query
@router.get("/", name="index")
def index(
request: Request,
category: str | None = Query(None),
q: str | None = Query(None, description="検索キーワード"),
page: int = Query(1, ge=1, description="ページ番号"),
size: int = Query(6, ge=1, le=50, description="1ページあたりの件数"),
db: Session = Depends(get_db)
):
"""ホームページ:カテゴリ絞り込み + キーワード検索 + ページネーション"""
posts_query = db.query(Post).order_by(Post.created_at.desc())
# カテゴリ絞り込み
if category:
posts_query = posts_query.join(Category).filter(Category.slug == category)
# キーワード検索
if q:
keyword = f'%{q.strip()}%'
posts_query = posts_query.filter(
or_(
Post.title.ilike(keyword),
Post.summary.ilike(keyword)
)
)
# ページネーション
total = posts_query.count()
total_pages = ceil(total / size)
skip = (page - 1) * size
posts = posts_query.offset(skip).limit(size).all()
return templates.TemplateResponse("index.html", {
"request": request,
"posts": posts,
"categories": db.query(Category).all(),
"category_slug": category or "",
"keyword": q or "",
"page": page,
"total_pages": total_pages,
"total": total
})
from sqlalchemy import or_
from math import ceil
from fastapi import APIRouter, Depends, Request, Query
@router.get("/", name="index")
def index(
request: Request,
category: str | None = Query(None),
q: str | None = Query(None, description="検索キーワード"),
page: int = Query(1, ge=1, description="ページ番号"),
size: int = Query(6, ge=1, le=50, description="1ページあたりの件数"),
db: Session = Depends(get_db)
):
"""ホームページ:カテゴリ絞り込み + キーワード検索 + ページネーション"""
posts_query = db.query(Post).order_by(Post.created_at.desc())
# カテゴリ絞り込み
if category:
posts_query = posts_query.join(Category).filter(Category.slug == category)
# キーワード検索
if q:
keyword = f'%{q.strip()}%'
posts_query = posts_query.filter(
or_(
Post.title.ilike(keyword),
Post.summary.ilike(keyword)
)
)
# ページネーション
total = posts_query.count()
total_pages = ceil(total / size)
skip = (page - 1) * size
posts = posts_query.offset(skip).limit(size).all()
return templates.TemplateResponse("index.html", {
"request": request,
"posts": posts,
"categories": db.query(Category).all(),
"category_slug": category or "",
"keyword": q or "",
"page": page,
"total_pages": total_pages,
"total": total
})
Query(1, ge=1)におけるgeは greater than or equal の略です。FastAPI のクエリパラメータは完全な数値制約をサポートしています:ge、le、gt、lt。ユーザーが page=0 を渡すと、FastAPI は自動的に 422 エラーを返します。
テンプレート内のページネーションナビゲーション
例
<!-- index.html の記事リストの下にページネーションナビゲーションを追加 -->
{% if total_pages > 1 %}
<div class="pagination">
{% if page > 1 %}
<a href="/?page={{ page - 1 }}&category={{ category_slug }}&q={{ keyword }}">← 前のページ</a>
{% endif %}
<span class="page-info">第 {{ page }} ページ / 全 {{ total_pages }} ページ</span>
{% if page < total_pages %}
<a href="/?page={{ page + 1 }}&category={{ category_slug }}&q={{ keyword }}">次のページ →</a>
{% endif %}
</div>
{% endif %}
{% if total_pages > 1 %}
<div class="pagination">
{% if page > 1 %}
<a href="/?page={{ page - 1 }}&category={{ category_slug }}&q={{ keyword }}">← 前のページ</a>
{% endif %}
<span class="page-info">第 {{ page }} ページ / 全 {{ total_pages }} ページ</span>
{% if page < total_pages %}
<a href="/?page={{ page + 1 }}&category={{ category_slug }}&q={{ keyword }}">次のページ →</a>
{% endif %}
</div>
{% endif %}
本章のまとめ
この章では、一覧ページの実用的な機能を実装しました:ilike 大文字小文字を区別しない検索、or_() による複数フィールドの複合検索、offset/limit による手動ページネーション(Flask の paginate の代替)、Query() によるクエリパラメータの範囲制約。
検索 + カテゴリ絞り込み + ページネーションは任意に組み合わせることができ、条件は失われません。
その他の拡張