• 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)
    <!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特地提供给我们的方便批量操作数据库的方式,效率非常高!!!

  • 相关阅读:
    SQL 查询两个时间段是否有交集的情况 三种写法
    c# 时间区间求并集
    uniapp 身份证识别 微信 百度 图片前端压缩 图片后端压缩
    Git命令大全
    构建android studio项目
    如何查tomcat进程和杀死进程
    mysql 备份 还原不了
    解决git extensions每次要输入用户名和密码
    JS string 转 Byte64[]
    Git cmd
  • 原文地址:https://www.cnblogs.com/baohanblog/p/12181659.html
Copyright © 2020-2023  润新知