如何在 Django 中创建自定义分页器

How to create custom paginator in django

我正在尝试使用 django 内置的分页器,但它不起作用,因为我没有使用数据库存储对象,我正在与其他 api...

创建一个网站

这是我的代码:

def index(request):
    response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json")
    data = response.json()
    p = Paginator(data, 3)
    pn = request.GET.get('page')
    print(pn, p, data)
    page_obj = p.get_page(pn)

    context = {
        'data': data,
        'page_obj': page_obj
    }
    return render(request, 'index.html', context)

如果需要,我需要创建自定义分页器吗?我应该怎么做?或者有解决办法吗?

https://docs.djangoproject.com/en/4.0/topics/pagination/#example 您可以将任何列表提供给分页器。

问题是 API 的响应不是 return 列表,而是列表位于服务器键下的对象。 解决方案:


def index(request):
    response = requests.get("https://www.hetzner.com/a_hz_serverboerse/live_data.json")
    data = response.json()['server']
    p = Paginator(data, 3)
    pn = request.GET.get('page')
    print(pn, p, data)
    page_obj = p.get_page(pn)

    context = {
        'data': data,
        'page_obj': page_obj
    }
    return render(request, 'index.html', context)