photocrowd / django-cursor-pagination

Cursor-based pagination for Django
BSD 3-Clause "New" or "Revised" License
158 stars 27 forks source link

How to use forward pagination and backwards pagination in an API #41

Closed habibi1981 closed 2 years ago

habibi1981 commented 2 years ago

How to use forward pagination and backwards pagination in an API?

patrick91 commented 2 years ago

@habibi1981 can you provide more details?

we have this example in the README:

def posts_api(request, after=None):
    qs = Post.objects.all()
    page_size = 10
    paginator = CursorPaginator(qs, ordering=('-created', '-id'))
    page = paginator.page(first=page_size, after=after)
    data = {
        'objects': [serialize_page(p) for p in page],
        'has_next_page': page.has_next,
        'last_cursor': paginator.cursor(page[-1])
    }
    return data

You can pass after to paginator.page to get results after a specific cursor.

In this example, we are returning the last_cursor which you can use to go to the next page. You can do the same thing for the first cursor, if you want to navigate back. The paginator supports a before param too

habibi1981 commented 2 years ago

I used the following code and my problem was solved: forward pagination : paginator.page(first=page_size, after=after)

backwards pagination: paginator.page(last=page_size, before=before)

patrick91 commented 2 years ago

awesome, I'll close the issue then!