Django之批量插入数据以及分页

批量插入数据


l = []
    for i in range(10000):
        l.append(models.Book2(name='第%s本书'%i))
    models.Book2.objects.bulk_create(l)  # 批量插入数据

urls.py

rom django.conf.urls import url
from django.contrib import admin

from app01 import views

urlpatterns = [
    url(r'^booklist/', views.book_list),
]

views.py

from app01 import models
def book_list(request):
    # 动态插入100000条数据
    l=[]
    for i in range(10000):
        l.append(models.Book2(name="第%s本书"%i))
    models.Book2.objects.bulk_create(l)
    # 查询所有的书籍展示到前端页面
    book_list=models.Book2.objects.all()
    return render(request,'booklist.html',locals())

models.py

from django.db import models
class Book2(models.Model):
    name=models.CharField(max_length=64)

执行manage.py命令创建表

菜单-tools-Run manager.py Task
$ makemigrations
$ migrate

booklist.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>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
   <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <table class="table table-hover table-bordered table-striped">
                <thead>
                    <tr>
                        <th>id</th>
                        <th>name</th>
                    </tr>
                </thead>
                <tbody>
                    {% for book in book_list %}
                    <tr>
                        <td>{{ book.pk }}</td>
                        <td>{{ book.name }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
</html>

分页

导入模块 from django.core.paginator import Paginator,EmptyPage

Paginator 实现分页功能,跳转到那一页默认情况下需要通过浏览器手动输入

EmptyPage: 跳转到那一页默认情况下需要通过浏览器手动输入,如果输入的页数是负数或者超出范围就会有一场场EmptyPage,主要用作捕获异常



版本1


urls.py

from django.conf.urls import url
from django.contrib import admin

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
]

models.py

from django.db import models


# Create your models here.

class Book(models.Model):
    title = models.CharField(max_length=32)
    price = models.DecimalField(decimal_places=2, max_digits=8)

    def __str__(self):
        return '对象:%s'%self.title

views.py

from django.shortcuts import render, HttpResponse

# Create your views here.
from .models import Book
from django.core.paginator import Paginator,EmptyPage

def index(request):
    # book_list = []
    # for i in range(100):
    #     book = Book(title='book_%s' % i, price=i * i)
    #     book_list.append(book)
    # Book.objects.bulk_create(book_list)
    booklist=Book.objects.all()


    # 分页器
    paginator=Paginator(booklist,106)
    print(paginator.count)  # 数据总数
    print(paginator.num_pages) # 总页数
    print(paginator.page_range) #页码的列表
    page_range=paginator.page_range

    try:
        current_pag=int(request.GET.get('page',1))
        page1=paginator.page(current_pag) # 第一页数据的对象列表

        # 显示某一页具体数据的两种方式:
        print(page1.object_list)
        # <QuerySet[ < Book: 对象:book_0 >, < Book: 对象:book_1 >, < Book: 对象:book_2 >, < Book: 对象:book_3 >, < Book: 对象:book_4 >] >

        for i in page1:
            print(i)
        # 对象:book_0
        # 对象:book_1
        # 对象:book_2
        # 对象:book_3
        # 对象:book_4

    except EmptyPage as e:
        page1=paginator.page(1)

    return render(request, 'index.html', {'page': page1,'page_range':page_range,'current_page':current_pag})

bootstrap中文网找到一个分页的样式 https://v3.bootcss.com/components/#pagination放入index.html,用户通过点击页码,就能跳转到页面


index.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>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
   <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <table class="table table-hover table-bordered table-striped">
                <thead>
                    <tr>
                        <th>id</th>
                        <th>title</th>
                        <th>price</th>
                    </tr>
                </thead>
                <tbody>
                    {% for book in page %}
                    <tr>
                        <td>{{ book.pk }}</td>
                        <td>{{ book.title }}</td>
                        <td>{{ book.price }}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
    <nav aria-label="Page navigation">
  <ul class="pagination">
    <li>
      <a href="?page={{ current_page|add:-1 }}" aria-label="Previous">
        <span aria-hidden="true">上一页</span>
      </a>
    </li>
      {% for item in page_range %}
          {% if current_page == item %}
              <li class="active"><a href="?page={{ item }}">{{ item }}</a></li>
          {% else %}
               <li><a href="?page={{ item }}">{{ item }}</a></li>
          {% endif %}
       {% endfor %}
    <li>
      <a href="?page={{ current_page|add:1}}" aria-label="Next">
        <span aria-hidden="true">下一页</span>
      </a>
    </li>
  </ul>
</nav>
</body>
</html>


最终版本

urls.py

from django.conf.urls import url
from django.contrib import admin

from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
]

views.py

from django.shortcuts import render, HttpResponse

# Create your views here.
from .models import Book
from django.core.paginator import Paginator, EmptyPage


def index(request):
    # book_list = []
    # for i in range(100):
    #     book = Book(title='book_%s' % i, price=i * i)
    #     book_list.append(book)
    # Book.objects.bulk_create(book_list)
    booklist = Book.objects.all()

    # 分页器
    paginator = Paginator(booklist, 60) # 分页,每一页106条数据对象
    print(paginator.count)  # 数据总数
    print(paginator.num_pages)  # 总页数
    print(paginator.page_range)  # 页码的列表
    last_page=paginator.page_range[-1]

    current_pag = int(request.GET.get('page', 1))
    if paginator.num_pages > 11:
        if current_pag - 5 < 1:
            page_range = range(1, 12)
        elif current_pag + 5 > paginator.num_pages:
            page_range = range(paginator.num_pages - 11, paginator.num_pages + 1)
        else:
            page_range = range(current_pag - 5, current_pag + 6)

    else:
        page_range = paginator.page_range


    try:
        page1 = paginator.page(current_pag)  # 某一页数据的对象列表

        print(page1.has_next) # page1这一页是否有下一页
        print(page1.next_page_number) # # page1这一页的下一页的页码
        print(page1.has_previous)  # page1这一页是否有上一页
        print(page1.previous_page_number) #page1这一页的上一页的代码

        # 显示某一页具体数据的两种方式:
        print(page1.object_list)
        # <QuerySet[ < Book: 对象:book_0 >, < Book: 对象:book_1 >, < Book: 对象:book_2 >, < Book: 对象:book_3 >, < Book: 对象:book_4 >] >

        for i in page1:
            print(i)
        # 对象:book_0
        # 对象:book_1
        # 对象:book_2
        # 对象:book_3
        # 对象:book_4



    except EmptyPage as e:
        page1 = paginator.page(1)

    return render(request, 'index.html', {'page': page1, 'page_range': page_range, 'current_page': current_pag,'last_page':last_page})

models.py

from django.db import models
class Book2(models.Model):
    name=models.CharField(max_length=64)

执行manage.py命令创建表

菜单-tools-Run manager.py Task
$ makemigrations
$ migrate

index.html

bootstap不会提示的问题,解决方案是在本地导入bootstrap文件

<!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>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <table class="table table-hover table-bordered table-striped">
                <thead>
                <tr>
                    <th>id</th>
                    <th>title</th>
                    <th>price</th>
                </tr>
                </thead>
                <tbody>
                {% for book in page %}
                    <tr>
                        <td>{{ book.pk }}</td>
                        <td>{{ book.title }}</td>
                        <td>{{ book.price }}</td>
                    </tr>
                {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <nav aria-label="Page navigation">
                <ul class="pagination center line-block">
                    <li>
                        <a href="?page=1" aria-label="Previous">
                            <span aria-hidden="true">第一页</span>
                        </a>
                    </li>
                    {% if page.has_previous %}
                        <li>
                            <a href="?page={{ page.previous_page_number }}" aria-label="Previous">
                                <span aria-hidden="true">上一页</span>
                            </a>
                        </li>
                    {% else %}
                        <li>
                            <span aria-hidden="true">上一页</span>
                        </li>
                    {% endif %}

                    {% for item in page_range %}
                        {% if current_page == item %}
                            <li class="active"><a href="?page={{ item }}">{{ item }}</a></li>
                        {% else %}
                            <li class="disabled"><a href="?page={{ item }}">{{ item }}</a></li>
                        {% endif %}
                    {% endfor %}
                    {% if page.has_next %}
                        <li>
                            <a href="?page={{ page.next_page_number }}" aria-label="Next">
                                <span aria-hidden="true">下一页</span>
                            </a>
                        </li>
                    {% else %}
                        <li class="disabled">
                            <span aria-hidden="true">下一页</span>
                        </li>
                    {% endif %}
                    <li>
                        <a href="?page={{ last_page }}" aria-label="Previous">
                            <span aria-hidden="true">最后一页</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</div>
</body>

</html>

posted @ 2019-11-06 01:44  cjw1219  阅读(318)  评论(0编辑  收藏  举报