Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does django paginator.num_pages returns one even when no objects are in db?

I want to create a paginator for my model but I want the pagination to appear only when there are models saved in my db.

I tried in my template

{% if page.paginator.num_pages != 0 %}
    #show pagination ul
{%endif%}

but didn't work. Apparently paginator object when created always has one page even if there aren't any objects in the objlist. I had to go around this using the object_list.count() method

{% if page.object_list.count != 0 %}
    #show pagination ul
{% endif %}

I don't have enough data to test it yet but is this the right way? Is there another one maybe better?

like image 612
Apostolos Avatar asked Nov 12 '13 11:11

Apostolos


People also ask

How does Django deal with pagination?

Note that you can give Paginator a list/tuple, a Django QuerySet , or any other object with a count() or __len__() method. When determining the number of objects contained in the passed object, Paginator will first try calling count() , then fallback to using len() if the passed object has no count() method.


2 Answers

If the paginator is instantiated with allow_empty_page=True, then it will have one page even if there are no objects. See the paginator docs for more info.

If you want to show the paginator when there is at least one object in the object list, then use:

{% if page.object_list.count %}
    #show pagination ul
{% endif %}

If you only want the paginator to appear when there is more than one page, then use:

{% if page.paginator.num_pages > 1 %}
    #show pagination ul
{%endif%}
like image 185
Alasdair Avatar answered Sep 18 '22 10:09

Alasdair


Instantiate Paginator with allow_empty_first_page=False (see documentation) This optional argument is True by default.

If allow_empty_first_page is True then an empty page is still a page. This means num_pages is one even though there are no objects. If allow_empty_first_page is False then num_pages can be zero.

You can then iterate through page.paginator.page_range as normal:

{% for page_number in page.paginator.page_range %}
    # show link to page
{% endfor %}

This won't show any pagination links as page_range will end up being an empty list.

like image 42
Simeon Visser Avatar answered Sep 18 '22 10:09

Simeon Visser