首页 > 解决方案 > django API 中的分页

问题描述

我需要帮助我正在从电影数据库中获取电影数据,到目前为止一切都很好。但我在分页上堆栈因为它只返回 20 个对象。我想在点击分页按钮时返回其他结果。

我尝试了很多方法但是我唯一能做到的就是通过在 URL ej 中传递参数来返回结果。?page=2 返回另外 20 个对象 ?page=3 返回另外 20 个对象。我想这样做,但使用分页按钮。我尝试使用 Django 分页,但它不起作用,因为它只从我的数据库返回对象而不是 API。

这是我在视图中的代码。我也在使用我在 github 上找到的一个小型库,但它没有文档。

我的代码在这里:

def peliculasPopulares(request):
tmdb = TMDb()
tmdb.language = 'es'
tmdb.api_key = 'my-api'
movie = Movie()
page = request.GET.get('page')
popular = movie.popular(page)


return render(request, 'peliculas/populares.html', {
    'title': 'populares',
    'populares': popular
})

标签: pythondjangoapivideo

解决方案


你可以使用 django 分页,它也有很好的文档,如果你需要一个好的模板,使用这个:

{% with page.paginator.num_pages as total_pages and page.number as current_page %}
Total page{{ total_pages|pluralize }}: {{ total_pages }}

{% if current_page > 3 %}
    First
{% else %} {% endif %} {% for counter in page.paginator.page_range %} {% if forloop.first and counter < current_page|add:-2 %}
...
{% elif counter == current_page|add:-1 or counter == current_page|add:-2 %}
    {{ counter }}
{% elif counter == current_page and total_pages != 1 %}
    {{ counter }}
{% elif current_page < counter and counter <= current_page|add:2 %}
    {{ counter }}
{% elif counter > current_page|add:2 and forloop.last %}
    ...
{% endif %} {% endfor %} {% if page.has_next and current_page|add:2 < total_pages %}
    Last
{% comment %} {% else %}
Last
{% endcomment %} {% endif %}
{% endwith %} {% block extra_heads %} {% endblock extra_heads %}

推荐阅读