项目需求:浏览器中访问django后端某一条url(如:127.0.0.1:8080/index/),实时朝数据库中生成一千条数据并将生成的数据查询出来,并展示到前端页面
| from django.conf.urls import url |
| from app01 import views |
| |
| urlpatterns = [ |
| url(r'^get_book/',views.get_book) |
| ] |
| from django.db import models |
| |
| class Book(models.Model): |
| title = models.CharField(max_length=64) |
| from django.shortcuts import render, HttpResponse, redirect |
| from app01 import models |
| |
| def get_book(request): |
| |
| for i in range(1000): |
| models.Book.objects.create(name='第%s本书'%i) |
| |
| book_queryset = models.Book.objcets.all() |
| return render(request,'get_book.html',locals()) |
| <!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' %}"> |
| <link rel="stylesheet" href="{% static 'dist/sweetalert.css' %}"> |
| <script src="{% static 'bootstrap-3.3.7-dist/js/bootstrap.min.js' %}"></script> |
| <script src="{% static 'dist/sweetalert.min.js' %}"></script> |
| </head> |
| <body> |
| <div class="container"> |
| <div class="row"> |
| <div class="col-md-8 col-md-offset-2"> |
| {% for book in book_queryset %} |
| <p>{{ book.title }}</p> |
| {% endfor %} |
| </div> |
| </div> |
| </div> |
| </body> |
| </html> |
上述代码书写完毕后启动django后端,浏览器访问,会发现浏览器会有一个明显的卡顿等待时间,这不是你的浏览器有问题也不是网速有问题,而是后端再不停的操作数据库,耗时较长,大概需要等待一段时间之后才能正常看到刚刚插入的1000条数据,很明显这样操作数据库的效率太低,那有没有一种方式是专门用来批量操作数据库的呢?答案是肯定的!