Search code examples
djangodjango-rest-frameworkdjango-viewsdjango-pagination

how to do a pagination-django with variable 'per_page'?


how to do a pagination with variable 'per_page'. For example, I have 100 articles I wish that the first page (1) contains 3 articles, the second page (2) contains 5 articles, will excite, me who draws of how many articles in each page. see the picture.enter image description here


Solution

  • I also have same problem, I can't search good answer from google, but I have a trick solution.

    If per_page is constant like 5, my code in view is:

    paginator = Paginator(articles, 5)
    
    for page_no in paginator.page_range:
      context_data = {
        'paginator': paginator,
        'page_no': page_no,
      }
    

    My solution is that create fake Paginator instance for every forloop, if per_page is variable and collected in num_articles_page list:

    page_no = 0
    row_counter = 0
    
    for row_num in num_articles_page:
      # count page_no for forloop
      page_no = page_no + 1
    
      # articles list in this page
      this_page_list = article_list[row_counter:]
    
      # count row for forloop
      row_counter = row_counter + row_num
    
      # push some fake item before this_page_list
      this_page_list = [None]*(page_no-1)*row_num + this_page_list
    
      # create Paginator instance in every forloop
      paginator = Paginator(this_page_list, row_num)
    
      if paginator.num_pages < page_no:
        break
    
      context_data = {
        'paginator': paginator,
        'page_no': page_no,
        'this_page': paginator.page(page_no),
      }
    

    so this_page will be correct in every page_no, you can use method like this_page.has_next() or this_page. has_other_pages()

    in template can also use:

    {% for this_article in paginator|page:page_no %}
    {% endfor %}
    
    {% if this_page. has_previous == False %}
    {% endif %}