這篇文章將為大家詳細講解有關使用Django怎么批量插入數(shù)據(jù),文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
views.py
from django.shortcuts import render, HttpResponse, redirect from app01 import models def get_book(request): # for循環(huán)插入1000條數(shù)據(jù) for i in range(1000): models.Book.objects.create(name='第%s本書'%i) book_queryset = models.Book.objects.all() # 將插入的數(shù)據(jù)再查詢出來 return render(request,'get_book.html',locals()) # 將查詢出來的數(shù)據(jù)傳遞給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后端,瀏覽器訪問,會發(fā)現(xiàn)瀏覽器會有一個明顯的卡頓等待時間,這是因為后端在不停的操作數(shù)據(jù)庫,耗時較長,大概需要等待一段時間之后才能正常看到剛剛插入的1000條數(shù)據(jù),很明顯這樣操作數(shù)據(jù)庫的效率太低,那有沒有一種方式是專門用來批量操作數(shù)據(jù)庫的呢?答案是肯定的!
bulk_create方法
將views.py中原先的視圖函數(shù)稍作變化
def get_book(request): l = [] for i in range(10000): l.append(models.Book(title='第%s本書'%i)) models.Book.objects.bulk_create(l) # 批量插入數(shù)據(jù) return render(request,'get_book.html',locals())
關于使用Django怎么批量插入數(shù)據(jù)就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網(wǎng)頁名稱:使用Django怎么批量插入數(shù)據(jù)-創(chuàng)新互聯(lián)
文章路徑:http://chinadenli.net/article46/dihchg.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供建站公司、動態(tài)網(wǎng)站、Google、網(wǎng)站維護、外貿建站、云服務器
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內容