項目需求:瀏覽器中訪問django后端某一條url(如:127.0.0.1:8080/get_book/),實時朝數據庫中生成一千條數據并將生成的數據查詢出來,并展示到前端頁面
views.py
1
2
3
4
5
6
7
8
9
|
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
1
2
3
4
5
6
|
from django.conf.urls import url from app01 import views urlpatterns = [ url(r '^get_book/' ,views.get_book) ] |
models.py
1
2
3
4
|
from django.db import models class get_book(models.Model): title = models.CharField(max_length = 64 ) |
get_book.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<!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中原先的視圖函數稍作變化
1
2
3
4
5
6
|
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特地提供給我們的方便批量操作數據庫的方式,效率非常高!!!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/baohanblog/p/12181659.html