1

I've learned a little about django pagination from here : https://docs.djangoproject.com/en/2.0/topics/pagination/#page-objects

And I want to know how to get the number of items in certain Page object.

I thought a way like this : Page.end_index() - Page.start_index() + 1

But I think maybe it is not good or inaccurate way to get result.

Is there good way to get correct result?

touchingtwist
  • 1,930
  • 4
  • 23
  • 38

3 Answers3

3

Something vaguely similar to:

Paginator(query, objects_per_page, current_page_number)

And then pass the resulting paginator object into the template.

Inside the paginator's init you'd want to do something similar to:

def __init__(self, query, objects_per_page, current_page_number):
    self.total = query.count()

    self.per_page = objects_per_page
    self.current_page_number = current_page_number
    self.lower_limit = objects_per_page * current_page_number
    self.upper_limit = objects_per_page * (current_page_number + 1)

    if self.upper_limit > self.total:
        self.upper_limit = self.total

    self.objects = query[self.lower_limit - 1:self.upper_limit - 1]

Then in the template you'd do something like this:

Showing {{paginator.lower_limit}}-{{paginator.upper_limit}} of {{paginator.total}}

I hope that gives you a general idea of how you can cleanly do this.

Adam Jaamour
  • 1,326
  • 1
  • 15
  • 31
Gangani Roshan
  • 583
  • 1
  • 8
  • 25
3

In template:

{{ page_obj.paginator.count }} # The total number of objects, across all pages
{{ page_obj.paginator.per_page }} # The number of objects every page
{{ page_obj.paginator.num_pages }} # The total number of pages.
Ykh
  • 7,567
  • 1
  • 22
  • 31
1

Probably len(page.object_list) is the easiest.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895