Django如何对dicts列表进行分页

问题描述 投票:1回答:3

我有这个函数,我从Stackoverflow Api获取数据,如下所示,我将它们显示在html表中。有没有办法对这个dicts列表进行分页,以便在每个页面上显示10个结果?

views.朋友:

def get_questions(request):
    context = {}
    url = 'https://api.stackexchange.com/2.2/questions'
    params = {  'fromdate':'1525858177',
                'todate':'1525904006',
                'order':'desc',
                'sort':'activity',
                'tagged':'python',
                'site':'stackoverflow'
            }
    r = requests.get(url, params=params).json()
    dataList = []
    for item in r['items']:
        dataList.append({
            'owner': item['owner']['display_name'],
            'title': item['title'],
            'creation_date': datetime.datetime.fromtimestamp(float(item['creation_date'])),
            'is_answered': item['is_answered'], # (yes / no)
            'view_count': item['view_count'],
            'score':item['score'],
            'link':item['link'],
            'answer_count':item['answer_count']
        })

    template = 'questions/questions_list.html'
    context['data'] = dataList
    return render(request,template,context)

questions_list.html:

  <table id="myTable" class="table table-hover">
    <thead>
      <tr>
        <th scope="col">Owner</th>
        <th scope="col">Title</th>
        <th scope="col">Creation date</th>
        <th scope="col">Is answered</th>
        <th scope="col">View count</th>
        <th scope="col">Score</th>
      </tr>
    </thead>
    <tbody>
        {% for d in data %}
      <tr>
        <td>{{ d.owner }}</td>
        <td><a href="{{ d.link }}" target="blank">{{ d.title }}</a></td>
        <td>{{ d.creation_date }}</td>
        <td>{{ d.is_answered|yesno:"yes,no" }}</td>
        <td>{{ d.view_count }}</td>
        <td>{{ d.score }}</td>
      </tr>
      {% endfor %}
    </tbody>
  </table> 
python django pagination
3个回答
2
投票

Django提供了一些类来帮助您管理分页数据 - 即分布在多个页面上的数据,使用“上一页/下一页”链接。这些类存在于django / core / paginator.py中。

为Paginator提供一个对象列表,以及您希望在每个页面上拥有的项目数量,它为您提供了访问每个页面的项目的方法:

>>> from django.core.paginator import Paginator
>>> objects = ['john', 'paul', 'george', 'ringo']
>>> p = Paginator(objects, 2)

>>> p.count
4
>>> p.num_pages
2
>>> type(p.page_range)
<class 'range_iterator'>
>>> p.page_range
range(1, 3)

>>> page1 = p.page(1)
>>> page1
<Page 1 of 2>
>>> page1.object_list
['john', 'paul']

>>> page2 = p.page(2)
>>> page2.object_list
['george', 'ringo']
>>> page2.has_next()
False
>>> page2.has_previous()
True
>>> page2.has_other_pages()
True
>>> page2.next_page_number()
Traceback (most recent call last):
...
EmptyPage: That page contains no results
>>> page2.previous_page_number()
1
>>> page2.start_index() # The 1-based index of the first item on this page
3
>>> page2.end_index() # The 1-based index of the last item on this page
4

>>> p.page(0)
Traceback (most recent call last):
...
EmptyPage: That page number is less than 1
>>> p.page(3)
Traceback (most recent call last):
...
EmptyPage: That page contains no results

我希望这些示例代码片段有助于解决您的查询!


2
投票

我的建议是使用datatables.net

它很容易安装,但仍然会在前端完成分页。

只需添加

<link rel="stylesheet" href="//cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />

<script src="//cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"> </script> 

另外,不要忘记添加jQuery。

然后只需调用一个简单的jQuery函数

$(document).ready( function () {
    $('#myTable').DataTable();
} );

0
投票

您可以使用基本DRF,覆盖基于类的视图ModelViewSet,添加分页类。然后您可以轻松自定义分页显示100,20,10等。

from rest_framework import views, viewsets, authentication, permissions,pagination   
class  A (viewsets.ModelViewSet):
          pagination_class = pagination.PageNumberPagination
          page_size = 100

       def get_questions(self, request, *args, **kwargs):
           #Your code here 
           #intercete the code and inject this here
           if request.GET.get('page', None) is not None:
              self.page_size = request.GET.get('page_size',self.page_size)
              page = self.paginate_queryset(self.queryset.order_by(order_by))
           else:
               #Something else
© www.soinside.com 2019 - 2024. All rights reserved.