Django 批量插入数据的实现方法

yipeiwu_com6年前Python基础

项目需求:浏览器中访问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' %}" rel="external nofollow" >
  <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}" rel="external nofollow" >
  <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>

上述代码书写完毕后启动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特地提供给我们的方便批量操作数据库的方式,效率非常高!!!

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python中多层嵌套列表的拆分方法

场景:有一个多层嵌套的列表如:[[23],[3,3],[22,22],1,123,[[123,a],2]] 拆分成: def splitlist(list): ''' 现...

利用python脚本如何简化jar操作命令

前言 本篇和大家分享的是使用python简化对jar包操作命令,封装成简短关键字或词,达到操作简便的目的。最近在回顾和构思shell脚本工具,后面一些文章应该会分享shell内容,希望大...

Python3 使用map()批量的转换数据类型,如str转float的实现

我们知道map() 会根据提供的函数对指定序列做映射。 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新...

Python将视频或者动态图gif逐帧保存为图片的方法

本文是基于opencv将视频和动态图gif保存为图像帧。可以根据输入视频格式的不同,修改第21行。        对动图的处理...

从零学python系列之数据处理编程实例(一)

要求:分别以james,julie,mikey,sarah四个学生的名字建立文本文件,分别存储各自的成绩,时间格式都精确为分秒,时间越短成绩越好,分别输出每个学生的无重复的前三个最好成绩...