python - 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
})
解决方案
你可以使用 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 %}
推荐阅读
- php - 需要记录丢失的密码更改请求
- ansible - 厨师 Nessus 代理安装
- java - 火花打印数据帧而不会耗尽内存
- python - 简单的头尾机器人
- git - MailChimp 安装在 magento 2.3 中通过 composer 安装时出错
- android - 如何在应用程序中使用 Android Car API
- javascript - 如何防止使用jsRender的客户端HTML编码从服务器编码已经编码的字符串
- testng - 从 CSV 文件执行 TestNG 测试用例
- sql - SQL 案例将 XML 打印到单行。需要多行
- javascript - 理解 Javascript/Typescript 类并扩展它们