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

yipeiwu_com5年前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中typing模块与类型注解的使用方法

实例引入 我们知道 Python 是一种动态语言,在声明一个变量时我们不需要显式地声明它的类型,例如下面的例子: a = 2 print('1 + a =', 1 + a) 运行...

django组合搜索实现过程详解(附代码)

django组合搜索实现过程详解(附代码)

一.简介 # 组合搜索 # 技术方向:自动化,测试,运维,前端 # 分类:Python Linux JavaScript OpenStack Node.js GO #...

python中format()函数的简单使用教程

python中format()函数的简单使用教程

先给大家介绍下python中format函数,在文章下面给大家介绍python.format()函数的简单使用 ---恢复内容开始--- python中format函数用于字符串的格式化...

解决PyCharm同目录下导入模块会报错的问题

在PyCharm2017中同目录下import其他模块,会出现No model named ...的报错,但实际可以运行 这是因为PyCharm不会将当前文件目录自动加入source_p...

python 实现视频流下载保存MP4的方法

如下所示: # -*- coding:utf-8 -*- import sys import os from glob import glob import requests...