API Reference
Paging & Ordering

Paging & Ordering Results

Control result pagination and sorting with limit, offset, and order_by parameters


Results of a query can be paged using the limit and offset query string parameters and ordered using the order_by parameter.

Example Usage

import payload
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
customers = pl.Account.order_by( pl.attr.created_at )[5:15]

Paging Parameters

AttributeDescription
limit=10Limit the number of results
offset=5Offset the results from the start of the set

Paging Examples

import payload
 
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
# Get first 10 customers
 
 
first_10 = pl.Account.all()[:10]
 
# Get customers 11-20
next_10 = pl.Account.all()[10:20]
 
# Using filter_by with explicit paging
customers = pl.Account.limit(10).offset(20).all()

Ordering Parameters

AttributeDescription
order_by=created_atResults Ordering

Ordering Examples

import payload
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
# Order by creation date (ascending)
 
 
customers = pl.Account.order_by(pl.attr.created_at).all()
 
# Order by creation date (descending)
customers = pl.Account.order_by(pl.attr.created_at.desc()).all()
 
# Multiple ordering criteria
customers = pl.Account.order_by(
    pl.attr.status,
    pl.attr.created_at.desc()
).all()

Combined Paging and Ordering

You can combine paging and ordering to get paginated, sorted results:

import payload
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
# Get customers 11-20, ordered by creation date (newest first)
 
 
customers = pl.Account.order_by(pl.attr.created_at.desc())[10:20]

Best Practices

Pagination

  • Use consistent page sizes: Keep your limit parameter consistent across requests
  • Handle empty results: Check if the returned array is empty to detect the end of results
  • Consider total count: Some endpoints may provide total count information in response headers

Ordering

  • Always specify ordering: For consistent pagination, always include an order_by parameter
  • Use unique fields for ordering: When possible, include a unique field (like id or created_at) in your ordering criteria
  • Consider performance: Ordering by indexed fields will perform better than non-indexed fields

Example Pagination Loop

import payload
pl = payload.Session('secret_key_3bW9...', api_version='v2')
 
def get_all_customers():
    customers = []
    offset = 0
    limit = 100
 
    while True:
        batch = pl.Account.filter_by(
            limit=limit,
            offset=offset,
            order_by='created_at'
        ).all()
 
        if not batch:
            break
 
        customers.extend(batch)
        offset += limit
 
    return customers