• Django 批量插入数据


    项目需求:浏览器中访问django后端某一条url(如:127.0.0.1:8080/get_book/),实时朝数据库中生成一千条数据并将生成的数据查询出来,并展示到前端页面

    views.py

    复制代码
    from django.shortcuts import render, HttpResponse, redirect
    from app01 import models
    
    def get_book(request):
      # for循环插入1000条数据
      for i in range(1000):
        models.Book.objects.create(name='第%s本书'%i)
      book_queryset = models.Book.objects.all()     # 将插入的数据再查询出来
      return render(request,'get_book.html',locals())  # 将查询出来的数据传递给html页面
    复制代码

    urls.py

    from django.conf.urls import url
    from app01 import views
    
    urlpatterns = [
      url(r'^get_book/',views.get_book)
    ]

    models.py

    from django.db import models
    
    class get_book(models.Model):
      title = models.CharField(max_length=64)
     get_book.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    {% load static %}
    <link rel="stylesheet" href="{% static 'bootstrap-3.3.7-dist/css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}">
    <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'dist/sweetalert.min.js' %}"></script>
    </head>
    <body>
    {% for book_obj in book_queryset %}
    <p>{{ book_obj.title }}</p>
    {% endfor %}
    </body>
    </html>

    get_book.html

    上述代码书写完毕后启动django后端,浏览器访问,会发现浏览器会有一个明显的卡顿等待时间,这是因为后端在不停的操作数据库,耗时较长,大概需要等待一段时间之后才能正常看到刚刚插入的1000条数据,很明显这样操作数据库的效率太低,那有没有一种方式是专门用来批量操作数据库的呢?答案是肯定的!

    bulk_create方法

    将views.py中原先的视图函数稍作变化

    def get_book(request):
        l = []
        for i in range(10000):
            l.append(models.Book(title='第%s本书'%i))
        models.Book.objects.bulk_create(l)  # 批量插入数据
            return render(request,'get_book.html',locals())

    代码修改完毕之后其他地方无需改动,重启django项目浏览器重新访问,你会立马发现数据量增大十倍的情况下页面出现的速度比上面还快。

    bulk_create方法是django orm特地提供给我们的方便批量操作数据库的方式,效率非常高!!!

  • 相关阅读:
    希望走过的路成为未来的基石
    第三次个人作业--用例图设计
    第二次结对作业
    第一次结对作业
    第二次个人编程作业
    第一次个人编程作业(更新至2020.02.07)
    Springboot vue 前后分离 跨域 Activiti6 工作流 集成代码生成器 shiro权限
    springcloud 项目源码 微服务 分布式 Activiti6 工作流 vue.js html 跨域 前后分离
    spring cloud springboot 框架源码 activiti工作流 前后分离 集成代码生成器
    java代码生成器 快速开发平台 二次开发 外包项目利器 springmvc SSM后台框架源码
  • 原文地址:https://www.cnblogs.com/wddxx/p/13802487.html
Copyright © 2020-2023  润新知