Django批量插入和分页器

【一】批量插入

【1】基础准备

(1)创建模型表

python 复制代码
from django.db import models
# Create your models here.

class User(models.Model):
    name = models.CharField(max_length=32)

(2)模板层代码

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
{#显示所有用户名称#}
{% for user in user_queryset %}
    <p>{{ user.name }}</p>
{% endfor %}

</body>
</html>

(3)路由层代码

python 复制代码
from django.contrib import admin
from django.urls import path

from app02 import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path("data/batch/", views.data_batch, name="data_batch")
]

(4)视图层代码

python 复制代码
from django.shortcuts import render, HttpResponse
# Create your views here.

from app02 import models
import time

def data_batch(request):
    # 批量插入数据

    # 查询所有数据
    user_queryset = models.User.objects.all()
    return render(request, 'data_batch.html', locals())

【2】批量插入数据

(1)老方法create

python 复制代码
# 批量插入数据
start_time = time.time()
total_count = 1000
for i in range(total_count):
    models.User.objects.create(name=f"bruce{i}")
print(f"插入数据{total_count}条,用时:{time.time() - start_time}s")
# 插入数据1000条,用时:6.759927034378052s

(2)新方法bulk_create

python 复制代码
# 批量插入数据
start_time = time.time()
total_count = 1000
user_list = []
for i in range(total_count):
    user_obj = models.User(name=f"bruce{i}")
models.User.objects.bulk_create(user_list)
print(f"插入数据{total_count}条,用时:{time.time() - start_time}s")
# 插入数据1000条,用时:0.012999773025512695s
  • 速度有明显的提高

【二】分页器

【1】自己写low版

(1)前端页面

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
{#展示数据#}
{% for user in user_queryset %}
	<p>{{ user.name }}</p>
{% endfor %}

{#展示分页器#}
<nav aria-label="Page navigation">
  <ul class="pagination">
    {{ html_li|safe }}
  </ul>
</nav>
</body>
</html>

(2)视图层

python 复制代码
from django.shortcuts import render
# Create your views here.
from app01 import models

def data_pagination(request):
    # 全部数据对象queryset
    user_queryset = models.User.objects.all()
    # 总数居量
    total_digit = user_queryset.count()
    # 每页的数据量
    per_page = 10
    # 总页数
    quotient, remainder = divmod(total_digit, per_page)
    total_page = quotient + (1 if remainder else + 0)
    print(f"total_page:{total_page}")
    # 现在的页数,对0、大于总页数、非数字等,进行修正
    now_page = min(total_page, max(1, int(request.GET.get('page', "1")) if request.GET.get("page", "1").isdigit() else 1))
    # 可选按钮数量(讲究对称,必须是奇数,且大于等于3)
    button_num = 5
    button_num = max(3, button_num if button_num % 2 else button_num - 1)
    # 中间页码,对前后进行校验
    half_button_num = button_num // 2
    mid_page = min(max(now_page, half_button_num + 1), total_page - half_button_num)
    print(f"mid_page:{mid_page}")
    # 对user_queryset进行切分
    user_queryset = user_queryset[(now_page - 1) * per_page: now_page * per_page]

    # li标签创建
    # 上一页
    if now_page <= 1:
        html_li = '<li class="disabled"><span aria-hidden="true"><<</span></li>'
    else:
        html_li = f'<li><a href="?page={now_page - 1}" aria-label="Previous"><span aria-hidden="true"><<</span></a></li>'
    # 中间分页器
    for i in range(mid_page - button_num // 2, mid_page + button_num // 2 + 1):
        if now_page == i:
            html_li += f'<li class="active"><a href="?page={i}">{i}</a></li>'
        else:
            html_li += f'<li><a href="?page={i}">{i}</a></li>'
    # 下一页
    if now_page >= total_page:
        html_li += '<li class="disabled"><span aria-hidden="true">>></span></li>'
    else:
        html_li += f'<li><a href="?page={now_page + 1}" aria-label="Next"><span aria-hidden="true">>></span></a></li>'
    return render(request, 'data_pagination.html', {"user_queryset": user_queryset, "html_li": html_li})

【2】专业版本(面向对象)

(1)说明

  • 当我们需要使用非django内置第三方功能 或者组件的代码时
  • 一般在根目录 或者应用目录下 创建一个utils文件夹
    • 在该文件夹下可以进行功能划分,再创建相应模块文件
    • 功能少也可以不划分,直接创建模块文件

(2)专业分页器

python 复制代码
class Pagination(object):
    def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
        """
        封装分页相关数据
        :param current_page: 当前页
        :param all_count:    数据库中的数据总条数
        :param per_page_num: 每页显示的数据条数
        :param pager_count:  最多显示的页码个数
        """
        try:
            current_page = int(current_page)
        except Exception as e:
            current_page = 1

        if current_page < 1:
            current_page = 1

        self.current_page = current_page

        self.all_count = all_count
        self.per_page_num = per_page_num

        # 总页码
        all_pager, tmp = divmod(all_count, per_page_num)
        if tmp:
            all_pager += 1
        self.all_pager = all_pager

        self.pager_count = pager_count
        self.pager_count_half = int((pager_count - 1) / 2)

        if current_page > all_pager:
            current_page = all_pager

    @property
    def start(self):
        return (self.current_page - 1) * self.per_page_num

    @property
    def end(self):
        return self.current_page * self.per_page_num

    def page_html(self):
        # 如果总页码 < 11个:
        if self.all_pager <= self.pager_count:
            pager_start = 1
            pager_end = self.all_pager + 1
        # 总页码  > 11
        else:
            # 当前页如果<=页面上最多显示11/2个页码
            if self.current_page <= self.pager_count_half:
                pager_start = 1
                pager_end = self.pager_count + 1

            # 当前页大于5
            else:
                # 页码翻到最后
                if (self.current_page + self.pager_count_half) > self.all_pager:
                    pager_end = self.all_pager + 1
                    pager_start = self.all_pager - self.pager_count + 1
                else:
                    pager_start = self.current_page - self.pager_count_half
                    pager_end = self.current_page + self.pager_count_half + 1

        page_html_list = []
        # 添加前面的nav和ul标签
        page_html_list.append('''
                    <nav aria-label='Page navigation>'
                    <ul class='pagination'>
                ''')
        first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
        page_html_list.append(first_page)

        if self.current_page <= 1:
            prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
        else:
            prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)

        page_html_list.append(prev_page)

        for i in range(pager_start, pager_end):
            if i == self.current_page:
                temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
            else:
                temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
            page_html_list.append(temp)

        if self.current_page >= self.all_pager:
            next_page = '<li class="disabled"><a href="#">下一页</a></li>'
        else:
            next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
        page_html_list.append(next_page)

        last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
        page_html_list.append(last_page)
        # 尾部添加标签
        page_html_list.append('''
                                           </nav>
                                           </ul>
                                       ''')
        return ''.join(page_html_list)

(3)使用

  • 先在根目录下创建utlis/mypage.y
    • 再将专业分页器代码复制进去
  • 视图层
    • 导入模块中的类
    • 创建实例
    • 进行数据切分
python 复制代码
def data_pagination(request):
    # 全部数据对象queryset
    user_queryset = models.User.objects.all()
    # 总数据量
    total_digit = user_queryset.count()
    # 每页的数据量
    per_page = 10
    # 总页数
    quotient, remainder = divmod(total_digit, per_page)
    total_page = quotient + (1 if remainder else + 0)
    # 现在的页数,对0、大于总页数、非数字等,进行修正
    now_page = min(total_page, max(1, int(request.GET.get('page', "1")) if request.GET.get("page", "1").isdigit() else 1))
    # 可选按钮数量(讲究对称,必须是奇数,且大于等于3)
    button_num = 5
    button_num = max(3, button_num if button_num % 2 else button_num - 1)

    # 生成Pagination对象
    page_obj = Pagination(current_page=now_page, all_count=total_digit, per_page_num=per_page, pager_count=button_num)
    # 对数据进行切分
    user_queryset = user_queryset[page_obj.start:page_obj.end]
    return render(request, 'data_pagination.html', locals())
  • 前端页面模板层
html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>

</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            {% for user in user_queryset %}
            <p>{{ user.name }}</p>
            {% endfor %}
            {{ page_obj.page_html|safe }}
        </div>
    </div>
</div>
</body>
</html>
相关推荐
bryant_meng2 小时前
【python】OpenCV—Image Moments
开发语言·python·opencv·moments·图片矩
KevinRay_2 小时前
Python超能力:高级技巧让你的代码飞起来
网络·人工智能·python·lambda表达式·列表推导式·python高级技巧
Captain823Jack3 小时前
nlp新词发现——浅析 TF·IDF
人工智能·python·深度学习·神经网络·算法·自然语言处理
资源补给站3 小时前
大恒相机开发(2)—Python软触发调用采集图像
开发语言·python·数码相机
Captain823Jack3 小时前
w04_nlp大模型训练·中文分词
人工智能·python·深度学习·神经网络·算法·自然语言处理·中文分词
刘大辉在路上3 小时前
突发!!!GitLab停止为中国大陆、港澳地区提供服务,60天内需迁移账号否则将被删除
git·后端·gitlab·版本管理·源代码管理
PieroPc4 小时前
Python 自动化 打开网站 填表登陆 例子
运维·python·自动化
VinciYan4 小时前
基于Jenkins+Docker的自动化部署实践——整合Git与Python脚本实现远程部署
python·ubuntu·docker·自动化·jenkins·.net·运维开发
测试老哥5 小时前
外包干了两年,技术退步明显。。。。
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
終不似少年遊*5 小时前
美国加州房价数据分析01
人工智能·python·机器学习·数据挖掘·数据分析·回归算法