批量插入数据
# 先创建一个Book表
class Book(models.Model):
title = models.CharField(max_length=32)
# ab_pl.html
{% for book_obj in book_queryset %}
<p>{{ book_obj.title }}</p>
{% endfor %}
# views.py
def ab_pl(request):
# 先给Book插入五百条数据
# for i in range(500):
models.Book.objects.create(title='第%s本书'%i)
# 再将所有的数据查询并展示到前端页面
# book_queryset = models.Book.objects.all()
# return render(request,'ab_pl.html',locals())
# 批量插入数据
book_list = []
for i in range(500):
book_obj = models.Book(title='第%s本书'%i)
book_list.append(book_obj)
models.Book.objects.bulk_create(book_list)
book_queryset = models.Book.objects.all()
return render(request,'ab_pl.html',locals())
# 当你想要批量插入数据的时候 使用orm给你提供的bulk_create能够大大的减少操作时间
自定义分页器
ab_pl.html
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{{ page_html|safe }}
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
views.py
def ab_pl(request):
# 分页
book_list = models.Book.objects.all()
# 想访问哪一页
current_page = request.GET.get('page',1) # 如果获取不到当前页码,就展示第一页
# 数据类型转换
try:
current_page = int(current_page)
except Exception:
current_page = 1
# 每条展示多少条
per_page_num = 10
# 起始位置
start_page = (current_page-1)*per_page_num
# 终止位置
end_page = current_page * per_page_num
# 计算出需要多少页
all_count = book_list.count()
page_count, more = divmod(all_count,per_page_num)
if more:
page_count += 1
page_html = ''
xxx = current_page
if current_page < 6:
current_page = 6
for i in range(current_page-5,current_page+6):
if current_page == i:
page_html += '<li class="active"><a href="?page=%s">%s</a></li>'%(i,i)
else:
page_html += '<li><a href="?page=%s">%s</a></li>'%(i,i)
book_queryset = book_list[start_page:end_page]
return render(request,'ab_pl.html',locals())