1批量插入数据:
User_list=[]
for i in range(100):
User_list.append(User(name='小明%s'%i,pwd='abcdefg%s'%i))
# 两个参数 (对象们,一次插几条)
User.objects.bulk_create(User_list)
2.分页器
from django.core.paginator import Paginator
# p=Paginator(users,10) # (【obj1,obj2...】object_list,一页显示数据条数)
# p.num_pages # 总页数
# p.page_range # 页数列表 range(1,11)
第x页的页对象
# s=p.page(1) #取到第x页 的页对象
# s.object_list #queryser对象 放的第一页的数据对象
# s.has_next()
# s.has_previous()
页数
# request.GET.get('yeshu') #当前页 <a href="?yesgy={{ foo }}">1</a>
# s.next_page_number() #下一页
# s.previous_page_number() #上一页
-干啥的?数据量大的话,可以分页获取,查看
基本写法:
后端:
-总数据拿出来
-生成分页器Paginator对象(对象里有属性和方法)
-生成当前页的对象,current_page=paginator.page(当前页码)
-取出前台传过来的页码,current_page_num = int(request.GET.get('page'))
-需要有异常捕获
-捕获到,把当前页码设置成第一页
def index(request):
book_list = models.Book.objects.all()
paginator = Paginator(book_list, 3)
# 如果页码数多,让它显示前5,后5,中间是当前在的页码
try:
current_page_num = int(request.GET.get('page'))
current_page = paginator.page(current_page_num)
print(current_page.object_list)
# 总页码数,大于11的时候
if paginator.num_pages >11:
# 当前页码数-5大于1的时候,page_range应该是?
if current_page_num-5<1:
page_range=range(1,12)
elif current_page_num+5>paginator.num_pages:
# 当前页码数+5大于总页码数,总页码数往前推11个
page_range=range(paginator.num_pages-10,paginator.num_pages+1)
else:
page_range = range(current_page_num - 5, current_page_num + 6)
else:
#小于11,有多少页,就显示多少页
page_range=paginator.page_range
except Exception as e:
current_page_num = 1
current_page = paginator.page(current_page_num)
return render(request, 'index_next.html', locals())
前端:
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<table class="table table-striped">
<thead>
<tr>
<th>书名</th>
<th>价格</th>
</tr>
</thead>
<tbody>
{% for book in current_page %}
<tr>
<td>{{ book.name }}</td>
<td>{{ book.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<nav aria-label="Page navigation">
<ul class="pagination">
{% if current_page.has_previous %}
<li>
{#<a href="/index/?page={{ current_page_num|add:-1 }}" aria-label="Previous">#}
<a href="/index/?page={{ current_page.previous_page_number }}" aria-label="Previous">
<span aria-hidden="true">上一页</span>
</a>
</li>
{% else %}
<li class="disabled">
<a href="" aria-label="Previous">
<span aria-hidden="true">上一页</span>
</a>
</li>
{% endif %}
{% for foo in page_range %}
{% if current_page_num == foo %}
{# 当前页码等于循环到的页码数,变色#}
<li class="active"><a href="/index/?page={{ foo }}">{{ foo }}</a></li>
{% else %}
<li><a href="?page={{ foo }}">{{ foo }}</a></li>
{% endif %}
{% endfor %}
{% if current_page.has_next %}
<li>
{# <a href="/index/?page={{ current_page_num|add:1 }}" aria-label="Next">#}
<a href="/index/?page={{ current_page.next_page_number }}" aria-label="Next">
<span aria-hidden="true">下一页</span>
</a>
</li>
{% else %}
<li class="disabled">
<a href="" aria-label="Next">
<span aria-hidden="true">下一页</span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>