Django Ninja Pagination: Next page exists?
Out of the box pagination Django Ninja's PageNumberPagination
serializes response in the following way:
{
"items": [
{...},
...
],
"count": 172
}
The question is how to determine if next page object exists? Sure, one can try to retrieve it from page size by the length of items
list, but this will not work if count is aliquot to the page size, so the next page will be empty list.
Is there a convenient way or workaround to get this information on the frontend?
For the sake of simplisity, let's just consider example from the docs:
from ninja.pagination import paginate, PageNumberPagination
@api.get('/users', response=List[UserSchema])
@paginate(PageNumberPagination)
def list_users(request):
return User.objects.all()
I don’t think you need to know if there’s a next page. It’s better to find the total number of pages and work from the current page and the total page count.
To calculate the page count correctly, you’ll need to use rounding math.ceil
.
import math
#get count item (172)
count_items = pagination["count"]
# 172/50 -> 3.44, math.ceil(3.44) -> 4
count_page = math.ceil(count_items/ITEMS_PER_PAGE)
#Here's an example of checking if there is a next page:
current_page = request.GET.get("page", 1)
has_next_page = current_page < count_page
You should also store the number of items per page in a separate variable in globals.py
. This will make it easier to adjust the page item count in the future.