Django 批量插入數(shù)據(jù)的實現(xiàn)方法
項目需求:瀏覽器中訪問django后端某一條url(如:127.0.0.1:8080/get_book/),實時朝數(shù)據(jù)庫中生成一千條數(shù)據(jù)并將生成的數(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ù)庫,耗時較長,大概需要等待一段時間之后才能正??吹絼倓偛迦氲?000條數(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項目瀏覽器重新訪問,你會立馬發(fā)現(xiàn)數(shù)據(jù)量增大十倍的情況下頁面出現(xiàn)的速度比上面還快。
bulk_create方法是django orm特地提供給我們的方便批量操作數(shù)據(jù)庫的方式,效率非常高!?。?/p>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python進行數(shù)據(jù)提取的方法總結(jié)
數(shù)據(jù)提取是分析師日常工作中經(jīng)常遇到的需求。如某個用戶的貸款金額,某個月或季度的利息總收入,某個特定時間段的貸款金額和筆數(shù),大于5000元的貸款數(shù)量等等。本篇文章介紹如何通過python按特定的維度或條件對數(shù)據(jù)進行提取,完成數(shù)據(jù)提取需求。2016-08-08
python爬蟲獲取小區(qū)經(jīng)緯度以及結(jié)構(gòu)化地址
這篇文章主要為大家詳細介紹了python爬蟲獲取小區(qū)經(jīng)緯度,以及結(jié)構(gòu)化的地址,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-12-12
Python數(shù)據(jù)結(jié)構(gòu)隊列解決約瑟夫斯問題
這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)隊列解決約瑟夫斯問題2023-02-02
Python學(xué)習(xí)之字典的常用方法總結(jié)
這篇文章主要為大家介紹了Python中字典的幾個常用方法總結(jié),文中的示例代碼講解詳細,對我們學(xué)習(xí)Python字典有一定幫助,需要的可以參考一下2022-03-03
Django開發(fā)web后端對比SpringBoot示例分析
這篇文章主要介紹了Django開發(fā)web后端對比SpringBoot示例分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-12-12

