If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

I wrote this function for code reuse purposes. It helps to run paginated queries:

def paginatedQuery(query, page=1, pagination=10, fields=[], filters={}):
    # Informed page below 1
    if page <= 0:
        redirect(URL(args=[page]))

    # Calculates maximum pages
    total = query.count()
    pages = total/pagination
    if total%pagination:
        pages+=1

    if page > pages:
        # Informed above maximum
        redirect(URL(args=[pages]))

    # Calculates the limits
    limit = (pagination*(page-1), (pagination*page))
    # Run paginated query
    result = query.select(
            limitby=limit,
            *fields,
            **filters
            )
    return (result, pages)

 

Usage:

# Fetches the second page with the name and address from all clients with
# pagination=20 and ordered by the client name
paginatedQuery(
    query=db(db.client),
    page=2,
    pagination=10,
    fields=(db.client.id, db.client.name),
    filters={'orderby': db.client.name}
)

# Fetches the first page with all the active addresses from all clients
# limiting the returned fields by: client id, name and all client_address
# fields
paginatedQuery(
    query=db(
        (db.client.id == db.client_address.client) &
        (db.client_address.active == True)
        )
    pagination=10,
    fields=(db.client.id, db.client.name, db.address.ALL),
    filters={'orderby': db.client.name|db.address.id}
)

 

That's it. And sorry for my bad english :)

Related slices

Comments (0)


Hosting graciously provided by:
Python Anywhere