キーワード検索とページネーション
この章では、SQLAlchemy を使って複合検索を実装し、Flask-SQLAlchemy に組み込まれたページネーション機能を使ってリストページを最適化する方法を学びます。
ilike — 大文字小文字を区別しない検索
SQLAlchemy のilikeメソッドは、大文字小文字を区別しないあいまい検索を実装します。
これは SQL のLIKE演算子に対応しますが、大文字小文字を無視します。
例
# 単一フィールド検索
posts = Post.query.filter(Post.title.ilike('%flask%')).all()
# 複数フィールドの複合検索:or_() は OR 関係を表す
from sqlalchemy import or_
posts = Post.query.filter(
or_(
Post.title.ilike('%flask%'),
Post.summary.ilike('%flask%')
)
).all()
posts = Post.query.filter(Post.title.ilike('%flask%')).all()
# 複数フィールドの複合検索:or_() は OR 関係を表す
from sqlalchemy import or_
posts = Post.query.filter(
or_(
Post.title.ilike('%flask%'),
Post.summary.ilike('%flask%')
)
).all()
| メソッド | SQL 演算子 | 大文字小文字を区別する |
|---|---|---|
| like() | LIKE | 区別する |
| ilike() | LIKE(大文字小文字を無視) | 区別しない |
| contains() | LIKE '%x%' | 区別する |
| startswith() | LIKE 'x%' | 区別する |
| in_() | IN | 完全一致 |
paginate — ページネーション
Flask-SQLAlchemy はpaginate()メソッドを提供しており、1回の呼び出しで現在のページのデータ + ページネーションのメタ情報を返します。
例
# main.py の index ビューを改良
page = request.args.get('page', 1, type=int) # 現在のページ番号(デフォルトは 1 ページ目)
per_page = 6 # 1ページあたり 6 件の記事を表示
# paginate(page, per_page, error_out)
# error_out=False:ページ番号が範囲外の場合、404 を返さずに空のリストを返す
pagination = posts_query.paginate(page=page, per_page=per_page, error_out=False)
posts = pagination.items # 現在のページの記事リスト
page = request.args.get('page', 1, type=int) # 現在のページ番号(デフォルトは 1 ページ目)
per_page = 6 # 1ページあたり 6 件の記事を表示
# paginate(page, per_page, error_out)
# error_out=False:ページ番号が範囲外の場合、404 を返さずに空のリストを返す
pagination = posts_query.paginate(page=page, per_page=per_page, error_out=False)
posts = pagination.items # 現在のページの記事リスト
pagination オブジェクトの属性
| 属性 | 型 | 説明 |
|---|---|---|
| items | リスト | 現在のページのデータ |
| page | int | 現在のページ番号 |
| pages | int | 総ページ数 |
| total | int | 総レコード数 |
| has_prev | bool | 前のページがあるかどうか |
| has_next | bool | 次のページがあるかどうか |
| prev_num | int | 前のページのページ番号 |
| next_num | int | 次のページのページ番号 |
完全な検索 + ページネーションビュー
例
# ファイルパス:app/blueprints/main.py
from flask import Blueprint, render_template, request
from sqlalchemy import or_
from app.models import Post, Category
main_bp = Blueprint('main', __name__)
@main_bp.route("/")
def index():
category_slug = request.args.get('category', '')
keyword = request.args.get('q', '').strip()
page = request.args.get('page', 1, type=int)
per_page = 6
# 基本クエリ
posts_query = Post.query.order_by(Post.created_at.desc())
# カテゴリ絞り込み
if category_slug:
posts_query = posts_query.join(Category).filter(Category.slug == category_slug)
# キーワード検索(タイトルまたは要約)
if keyword:
posts_query = posts_query.filter(
or_(
Post.title.ilike(f'%{keyword}%'),
Post.summary.ilike(f'%{keyword}%')
)
)
# ページネーション
pagination = posts_query.paginate(
page=page, per_page=per_page, error_out=False)
posts = pagination.items
return render_template('index.html',
posts=posts, pagination=pagination,
categories=Category.query.all(),
category_slug=category_slug, keyword=keyword)
from flask import Blueprint, render_template, request
from sqlalchemy import or_
from app.models import Post, Category
main_bp = Blueprint('main', __name__)
@main_bp.route("/")
def index():
category_slug = request.args.get('category', '')
keyword = request.args.get('q', '').strip()
page = request.args.get('page', 1, type=int)
per_page = 6
# 基本クエリ
posts_query = Post.query.order_by(Post.created_at.desc())
# カテゴリ絞り込み
if category_slug:
posts_query = posts_query.join(Category).filter(Category.slug == category_slug)
# キーワード検索(タイトルまたは要約)
if keyword:
posts_query = posts_query.filter(
or_(
Post.title.ilike(f'%{keyword}%'),
Post.summary.ilike(f'%{keyword}%')
)
)
# ページネーション
pagination = posts_query.paginate(
page=page, per_page=per_page, error_out=False)
posts = pagination.items
return render_template('index.html',
posts=posts, pagination=pagination,
categories=Category.query.all(),
category_slug=category_slug, keyword=keyword)
クエリパラメータは URL を介して渡されます(例:
/?q=flask&page=2)。ページネーションナビのリンクには現在の検索パラメータとカテゴリパラメータを含める必要があります。そうしないと、ページをめくった後に条件が失われます。
テンプレートの検索ボックスとページネーションナビ
例
<!-- ファイルパス:app/templates/index.html -->
{% extends 'base.html' %}
{% block title %}サンプル ブログ - ホームページ{% endblock %}
{% block content %}
<h2 class="section-title">最新記事</h2>
<!-- 検索ボックス -->
<div class="search-bar">
<form method="get" action="{{ url_for('main.index') }}">
<input type="text" name="q" value="{{ keyword }}"
placeholder="記事のタイトルまたは要約を検索..." class="search-input">
{% if keyword %}
<a href="{{ url_for('main.index', category=category_slug) }}" class="clear-btn">✕</a>
{% endif %}
</form>
</div>
<!-- カテゴリ絞り込み -->
<div class="category-bar">
<a href="{{ url_for('main.index', q=keyword) }}"
class="{% if not category_slug %}active{% endif %}">すべて</a>
{% for cat in categories %}
<a href="{{ url_for('main.index', category=cat.slug, q=keyword) }}"
class="{% if category_slug == cat.slug %}active{% endif %}">
{{ cat.name }}
</a>
{% endfor %}
</div>
<p class="result-info">
合計 {{ pagination.total }} 件の記事
{% if keyword %}、「{{ keyword }}」を検索{% endif %}
</p>
{% if posts %}
<div class="article-grid">
{% for post in posts %}
<a href="{{ url_for('posts.post_detail', post_id=post.id) }}" class="card-link">
<div class="article-card">
<div class="card-content">
<span class="card-category">{{ post.category.name }}</span>
<h3>{{ post.title }}</h3>
<p>{{ post.summary|truncate(80) }}</p>
<span class="card-date">{{ post.created_at.strftime('%Y-%m-%d') }}</span>
</div>
</div>
</a>
{% endfor %}
</div>
<!-- ページネーションナビ -->
{% if pagination.pages > 1 %}
<div class="pagination">
{% if pagination.has_prev %}
<a href="{{ url_for('main.index', page=pagination.prev_num, category=category_slug, q=keyword) }}">← 前のページ</a>
{% endif %}
{% for page_num in range(1, pagination.pages + 1) %}
{% if page_num == pagination.page %}
<span class="current">{{ page_num }}</span>
{% else %}
<a href="{{ url_for('main.index', page=page_num, category=category_slug, q=keyword) }}">{{ page_num }}</a>
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<a href="{{ url_for('main.index', page=pagination.next_num, category=category_slug, q=keyword) }}">次のページ →</a>
{% endif %}
</div>
{% endif %}
{% else %}
<p class="empty-tip">一致する記事が見つかりませんでした。</p>
{% endif %}
{% endblock %}
{% extends 'base.html' %}
{% block title %}サンプル ブログ - ホームページ{% endblock %}
{% block content %}
<h2 class="section-title">最新記事</h2>
<!-- 検索ボックス -->
<div class="search-bar">
<form method="get" action="{{ url_for('main.index') }}">
<input type="text" name="q" value="{{ keyword }}"
placeholder="記事のタイトルまたは要約を検索..." class="search-input">
{% if keyword %}
<a href="{{ url_for('main.index', category=category_slug) }}" class="clear-btn">✕</a>
{% endif %}
</form>
</div>
<!-- カテゴリ絞り込み -->
<div class="category-bar">
<a href="{{ url_for('main.index', q=keyword) }}"
class="{% if not category_slug %}active{% endif %}">すべて</a>
{% for cat in categories %}
<a href="{{ url_for('main.index', category=cat.slug, q=keyword) }}"
class="{% if category_slug == cat.slug %}active{% endif %}">
{{ cat.name }}
</a>
{% endfor %}
</div>
<p class="result-info">
合計 {{ pagination.total }} 件の記事
{% if keyword %}、「{{ keyword }}」を検索{% endif %}
</p>
{% if posts %}
<div class="article-grid">
{% for post in posts %}
<a href="{{ url_for('posts.post_detail', post_id=post.id) }}" class="card-link">
<div class="article-card">
<div class="card-content">
<span class="card-category">{{ post.category.name }}</span>
<h3>{{ post.title }}</h3>
<p>{{ post.summary|truncate(80) }}</p>
<span class="card-date">{{ post.created_at.strftime('%Y-%m-%d') }}</span>
</div>
</div>
</a>
{% endfor %}
</div>
<!-- ページネーションナビ -->
{% if pagination.pages > 1 %}
<div class="pagination">
{% if pagination.has_prev %}
<a href="{{ url_for('main.index', page=pagination.prev_num, category=category_slug, q=keyword) }}">← 前のページ</a>
{% endif %}
{% for page_num in range(1, pagination.pages + 1) %}
{% if page_num == pagination.page %}
<span class="current">{{ page_num }}</span>
{% else %}
<a href="{{ url_for('main.index', page=page_num, category=category_slug, q=keyword) }}">{{ page_num }}</a>
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<a href="{{ url_for('main.index', page=pagination.next_num, category=category_slug, q=keyword) }}">次のページ →</a>
{% endif %}
</div>
{% endif %}
{% else %}
<p class="empty-tip">一致する記事が見つかりませんでした。</p>
{% endif %}
{% endblock %}
本章のまとめ
この章では、リストページの実用的な機能を習得しました:ilike による大文字小文字を区別しない検索、or_() による複数フィールドの複合検索、paginate() によるページネーションクエリ、テンプレートでのページネーションナビのレンダリングとフィルタパラメータの保持です。
検索 + カテゴリ絞り込み + ページネーションは、3つを任意に組み合わせることができ、条件が失われることはありません。
その他の拡張