Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Keyword Search and Pagination

Keyword Search and Pagination

In this chapter you will learn to implement combined search with SQLAlchemy and optimize the list page with Flask-SQLAlchemy's built-in pagination.


ilike — Case-Insensitive Search

SQLAlchemy's ilike method implements case-insensitive fuzzy matching.

It corresponds to SQL's LIKE operator, but ignores case.

Example

Single-field search

posts

=

Post.

query

.

filter

(

Post.

title

.

ilike

(

'%flask%'

)

)

.

all

(

)

Multi-Field Combined Search: or_() represents an OR relationship

from

sqlalchemy

import

or_

posts

=

Post.

query

.

filter

(

    or_

(

        Post.

title

.

ilike

(

'%flask%'

)

,

        Post.

summary

.

ilike

(

'%flask%'

)

   

)

)

.

all

(

)

Method SQL Operator Case Sensitivity
like() LIKE to distinguish them
ilike() LIKE (case-insensitive) Case-insensitive
contains() LIKE '%x%' to distinguish them
startswith() LIKE 'x%' to distinguish them
in_() IN Exact match

paginate — Pagination

Flask-SQLAlchemy provides the paginate() method, which returns the current page's data + pagination metadata in one call.

Example

Refactoring the index View from main.py

page

=

request.

args

.

get

(

'page'

,

1

,

type

=

int

)

 

Current page number (default page 1)

per_page

=

6

                                   

Show 6 articles per page

paginate(page, per_page, error_out)

error_out=False: when the page number is out of range, return an empty list instead of a 404

pagination

=

posts_query.

paginate

(

page

=

page

,

per_page

=

per_page

,

error_out

=

False

)

posts

=

pagination.

items

   

The article list for the current page

pagination Object Attributes

property Type Description
items List Data on the current page
page int Current page number
pages int Total number of pages
total int Total number of records
has_prev bool Whether there is a previous page
has_next bool Whether there is a next page
prev_num int Previous page number
next_num int Next page number

Complete search + pagination view

Example

File path: 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

   

Basic query

    posts_query

=

Post.

query

.

order_by

(

Post.

created_at

.

desc

(

)

)

   

Category filtering

   

if

category_slug:

        posts_query

=

posts_query.

join

(

Category

)

.

filter

(

Category.

slug

==

category_slug

)

   

Keyword search (title or summary)

   

if

keyword

:

        posts_query

=

posts_query.

filter

(

            or_

(

                Post.

title

.

ilike

(

f

'%{keyword}%'

)

,

                Post.

summary

.

ilike

(

f

'%{keyword}%'

)

           

)

       

)

   

Print

    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

)

Query parameters are passed through the URL (e.g., /?q=flask&page=2), the pagination navigation links must carry the current search and category parameters, otherwise the conditions will be lost after switching pages.


Search Box and Pagination Navigation in the Template

Example

{% extends 'base.html' %}

{% block title %}RUNOOB Blog - Home{% endblock %}

{% block content %}

Latest Articles

    A total of {{ pagination.total }} articles

    {% if keyword %}, search "{{ keyword }}"{% endif %}

{% if posts %}

    {% for post in posts %}

   

       

           

               

{{ post.category.name }}

               

{{ post.title }}

               

{{ post.summary|truncate(80) }}

               

{{ post.created_at.strftime('%Y-%m-%d') }}

           

       

   

    {% endfor %}

{% if pagination.pages > 1 %}

{% endif %}

{% else %}

No matching articles found.

{% endif %}

{% endblock %}


Chapter Summary

In this chapter you mastered practical list-page features: ilike case-insensitive search, or_() multi-field combined search, paginate() paginated queries, and rendering pagination navigation in templates while preserving filter parameters.

Search + category filtering + pagination can be combined in any way, and conditions will not be lost.