Search code examples
pythondjango-rest-frameworkpaginationlimitoffset

How to change LimitOffsetPagination


I need to customize LimitOffsetPagination so it will show every time only unique objects. So for example, as default it works like this:

Total customers: 24
Offset=0 Limit=5 => 1,2,3,4,5
Offset=1 Limit=5 => 2,3,4,5,6

But I need it to work by this way (maybe I should change the way it slices, but I don't know how):

Total customers: 24
Offset=0 Limit=5 => 1,2,3,4,5
Offset=1 Limit=5 => 6,7,8,9,10


Solution

  • What you are asking for is just standard PageNumberPagination, and this is not related to uniqueness.

    LimitOffset describes an offset, # of records from the start and limit, number of rows to return. This maps directly into SQL as:

    SELECT * FROM table LIMIT 10 OFFSET 100
    

    Because of this, these two are equivalent:

    • my/url/?page=1&page_size=5
    • my/url/?offset=5&limit=5

    Use the standard PageNumberPagination, and change the page # / size parameter names if you really need to. I would suggest not doing that, since limit/offset has a very direct analog in SQL, is a standard, and it would be confusing.

    If you want to use the PageNumberPagination method with a user-settable page size you need to make a custom pagination class and define the page_size parameter:

    class MyPageNumberPagination(PageNumberPagination):
        page_size_query_param = "page_size"
        page_size = 5  # default size
        max_page_size = 100
    
    # A version which pretends to be limit/offset pagination
    class PageNumberAsLimitOffset(PageNumberPagination):
        page_query_param = "offset"   # this is the "page"
        page_size_query_param="limit" # this is the "page_size"
        page_size = 5
        max_page_size = 100
        
    # Override the DRF default pagination
    REST_FRAMEWORK = {
        ...
        "DEFAULT_PAGINATION_CLASS": "project.drf.pagination.MyPageNumberPagination"
    }