欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

項(xiàng)目需求:瀏覽器中訪問(wèn)django后端某一條url(如:127.0.0.1:8080/get_book/),實(shí)時(shí)朝數(shù)據(jù)庫(kù)中生成一千條數(shù)據(jù)并將生成的數(shù)據(jù)查詢出來(lái),并展示到前端頁(yè)面

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ù)再查詢出來(lái)
  return render(request,'get_book.html',locals()) # 將查詢出來(lái)的數(shù)據(jù)傳遞給html頁(yè)面

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>

上述代碼書寫完畢后啟動(dòng)django后端,瀏覽器訪問(wèn),會(huì)發(fā)現(xiàn)瀏覽器會(huì)有一個(gè)明顯的卡頓等待時(shí)間,這是因?yàn)楹蠖嗽诓煌5牟僮鲾?shù)據(jù)庫(kù),耗時(shí)較長(zhǎng),大概需要等待一段時(shí)間之后才能正??吹絼倓偛迦氲?000條數(shù)據(jù),很明顯這樣操作數(shù)據(jù)庫(kù)的效率太低,那有沒有一種方式是專門用來(lái)批量操作數(shù)據(jù)庫(kù)的呢?答案是肯定的!

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())

代碼修改完畢之后其他地方無(wú)需改動(dòng),重啟django項(xiàng)目瀏覽器重新訪問(wèn),你會(huì)立馬發(fā)現(xiàn)數(shù)據(jù)量增大十倍的情況下頁(yè)面出現(xiàn)的速度比上面還快。

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

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

相關(guān)文章

最新評(píng)論