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'll learn to implement combined search with SQLAlchemy and pagination with offset/limit.


ilike case-insensitive search

Example

Single-field search

posts

=

db.

query

(

Post

)

.

filter

(

Post.

title

.

ilike

(

f

'%{keyword}%'

)

)

.

all

(

)

Multi-field combined search (OR relationship)

from

sqlalchemy

import

or_

posts

=

db.

query

(

Post

)

.

filter

(

    or_

(

        Post.

title

.

ilike

(

f

'%{keyword}%'

)

,

        Post.

summary

.

ilike

(

f

'%{keyword}%'

)

   

)

)

.

all

(

)


offset/limit pagination

Flask-SQLAlchemy provides a convenient .paginate() method.

FastAPI uses native SQLAlchemy and requires manual pagination with offset + limit.

Pagination method Flask-SQLAlchemy FastAPI (native SQLAlchemy)
Get the current page's data .paginate(page, per_page).items .offset(skip).limit(per_page).all()
Total number of records pagination.total query.count()
Total number of pages pagination.pages Manual calculation: math.ceil(total / per_page)

Pagination formula

Example

import

math

from

fastapi

import

Query

def

get_pagination

(

page:

int

=

1

,

size:

int

=

6

)

:

   

"""
    Calculate pagination parameters
    page: current page number (starting from 1)
    size: number of items per page
    """

    skip

=

(

page -

1

)

Number of records to skip

   

return

skip

,

size

Usage examples

skip

,

limit

=

get_pagination

(

page

=

2

,

size

=

6

)

skip = 6, limit = 6 → skip the first 6 records, take records 7-12


Complete search + pagination view

Example

File path: routers/posts.py (extend the index route)

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

=

"Search keyword"

)

,

    page:

int

=

Query

(

1

,

ge

=

1

,

description

=

"Page number"

)

,

    size:

int

=

Query

(

6

,

ge

=

1

,

le

=

50

,

description

=

"Items per page"

)

,

    db: Session

=

Depends

(

get_db

)

)

:

   

"""Homepage: category filter + keyword search + pagination"""

    posts_query

=

db.

query

(

Post

)

.

order_by

(

Post.

created_at

.

desc

(

)

)

   

Category filtering

   

if

category:

        posts_query

=

posts_query.

join

(

Category

)

.

filter

(

Category.

slug

==

category

)

   

Keyword search

   

if

q:

       

keyword

=

f

'%{q.strip()}%'

        posts_query

=

posts_query.

filter

(

            or_

(

                Post.

title

.

ilike

(

keyword

)

,

                Post.

summary

.

ilike

(

keyword

)

           

)

       

)

   

Print

    total

=

posts_query.

count

(

)

    total_pages

=

ceil

(

total / size

)

    skip

=

(

page -

1

)

    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) The ge is short for greater than or equal. FastAPI query parameters support full numeric constraints: ge, le, gt, lt. If the user passes page=0, FastAPI automatically returns a 422 error.


Pagination navigation in templates

Example

{% if total_pages > 1 %}

{% endif %}


Chapter Summary

In this chapter you implemented the practical features of the list page: ilike case-insensitive search, or_() multi-field combined search, offset/limit manual pagination (replacing Flask's paginate), and using Query() to constrain the range of query parameters.

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