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特地提供給我們的方便批量操作數據庫的方式,效率非常高!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM