亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Django 批量插入數(shù)據(jù)的實(shí)現(xiàn)方法

 更新時(shí)間:2020年01月12日 09:21:44   作者:Hank·Paul  
這篇文章主要介紹了Django 批量插入數(shù)據(jù)的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

項(xiàng)目需求:瀏覽器中訪問django后端某一條url(如:127.0.0.1:8080/get_book/),實(shí)時(shí)朝數(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)瀏覽器會有一個(gè)明顯的卡頓等待時(shí)間,這是因?yàn)楹蠖嗽诓煌5牟僮鲾?shù)據(jù)庫,耗時(shí)較長,大概需要等待一段時(shí)間之后才能正常看到剛剛插入的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項(xiàng)目瀏覽器重新訪問,你會立馬發(fā)現(xiàn)數(shù)據(jù)量增大十倍的情況下頁面出現(xiàn)的速度比上面還快。

bulk_create方法是django orm特地提供給我們的方便批量操作數(shù)據(jù)庫的方式,效率非常高!?。?/p>

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論