django中Paginator怎么用
时间: 2023-12-04 07:03:54 浏览: 78
django的分页器Paginator 从django中导入类
Paginator是Django中的一个分页工具,可以将查询结果按照每页显示的数量进行分页显示。使用方法如下:
1. 引入Paginator和EmptyPage异常:
```python
from django.core.paginator import Paginator, EmptyPage
```
2. 在视图函数中进行查询:
```python
from .models import MyModel
def my_view(request):
my_objects = MyModel.objects.all()
paginator = Paginator(my_objects, 10) # 每页显示10条数据
page = request.GET.get('page') # 获取页码
try:
my_objects = paginator.page(page)
except EmptyPage:
my_objects = paginator.page(paginator.num_pages) # 超出范围则显示最后一页
return render(request, 'my_template.html', {'my_objects': my_objects})
```
3. 在模板中进行渲染:
```html
{% for my_object in my_objects %}
<!-- 显示数据 -->
{% endfor %}
<!-- 分页链接 -->
<div class="pagination">
<span class="step-links">
{% if my_objects.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={{ my_objects.previous_page_number }}">previous</a>
{% endif %}
<span class="current-page">
Page {{ my_objects.number }} of {{ my_objects.paginator.num_pages }}.
</span>
{% if my_objects.has_next %}
<a href="?page={{ my_objects.next_page_number }}">next</a>
<a href="?page={{ my_objects.paginator.num_pages }}">last »</a>
{% endif %}
</span>
</div>
```
希望以上内容能够帮助你解决问题。
阅读全文