批量插入 bulk_create()
# urls.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
#批量插入
path('ab_pl',views.ab_pl)
]
#views.py
def ab_pl(request):
# 先给Book表插入一千条数据
for i in range(1000):
models.Book.objects.create(title='第%s本书' % i)
# 再将所有的数据查询并展示到前端页面
book_queryset = models.Book.objects.all()
return render(request,'ab_pl.html',locals())
# models.py
class Book(models.Model):
title = models.CharField(max_length=32)
{% for book_obj in book_queryset %}
<p>{{ book_obj.title }}</p>
{% endfor %}
上述代码插入数据,需要一定时间,效率低下
bulk_create()
def ab_pl(request):
"""批量插入"""
book_list = []
for i in range(1000):
book_obj = models.Book(title='第%s本书' % i)
book_list.append(book_obj)
models.Book.objects.bulk_create(book_list)
return render(request, 'ab_pl.html', locals())
"""
当想要批量插入数据时候,使用orm提供的bulk_create()能够大大的减少操作时间
"""
标签:Book,ab,批量,models,create,bulk,book,pl
From: https://www.cnblogs.com/zaosong/p/16976489.html