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>
相关推荐
龙哥说跨境25 分钟前
如何利用指纹浏览器爬虫绕过Cloudflare的防护?
服务器·网络·python·网络爬虫
monkey_meng25 分钟前
【Rust中的迭代器】
开发语言·后端·rust
余衫马28 分钟前
Rust-Trait 特征编程
开发语言·后端·rust
monkey_meng32 分钟前
【Rust中多线程同步机制】
开发语言·redis·后端·rust
小白学大数据40 分钟前
正则表达式在Kotlin中的应用:提取图片链接
开发语言·python·selenium·正则表达式·kotlin
flashman91142 分钟前
python在word中插入图片
python·microsoft·自动化·word
菜鸟的人工智能之路1 小时前
桑基图在医学数据分析中的更复杂应用示例
python·数据分析·健康医疗
懒大王爱吃狼2 小时前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍
秃头佛爷3 小时前
Python学习大纲总结及注意事项
开发语言·python·学习
深度学习lover4 小时前
<项目代码>YOLOv8 苹果腐烂识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果腐烂识别