Django从理论到实战(part47)--ListView类
學(xué)習(xí)筆記,僅供參考,有錯(cuò)必糾
參考自:Django打造大型企業(yè)官網(wǎng)–Huang Y;
文章目錄
- 類視圖
- ListView類
- 舉個(gè)例子
- Paginator和Page類
- Paginator常用屬性
- Page常用屬性和方法
- 舉個(gè)例子
類視圖
ListView類
在網(wǎng)站開發(fā)中,經(jīng)常會(huì)出現(xiàn)需要列出某個(gè)表中的一些數(shù)據(jù)作為列表展示出來,在Django中可以使用ListView類來幫我們快速實(shí)現(xiàn)這種需求。
舉個(gè)例子
首先,我們創(chuàng)建一個(gè)book應(yīng)用,并對(duì)該APP在settings.py中進(jìn)行配置:
python manage.py startapp book在book應(yīng)用的models.py文件下,敲入如下代碼:
from django.db import models# Create your models here.class Article(models.Model):title = models.CharField(max_length = 30)content = models.TextField()create_time = models.DateTimeField(auto_now_add = True)進(jìn)行遷移操作:
python manage.py makemigrations python manage.py migrate我們用Navicat連接sqlite數(shù)據(jù)庫:
打開數(shù)據(jù)庫連接,并打開庫,可以看到存在book_article表:
現(xiàn)在,我們?cè)赽ook應(yīng)用的views.py文件中創(chuàng)建視圖函數(shù)add_book,用來添加書籍:
from django.shortcuts import render from django.http import HttpResponse from .models import Article # Create your views here.def add_book(request):articles = []for x in range(0, 102):article = Article(title = "標(biāo)題: %s" % x, content = "內(nèi)容:%s" % x)articles.append(article)Article.objects.bulk_create(articles)return HttpResponse("<h2>Are you OK?</h2>")在book應(yīng)用的views.py文件中創(chuàng)建ArticleListView類,它繼承自ListView類:
class ArticleListView(ListView):model = Article#重寫model類屬性,指定這個(gè)列表是給哪個(gè)模型的template_name = "book_list.html"#指定這個(gè)列表的模板context_object_name = "articles"#在模板文件中的名字paginate_by = 10#指定這個(gè)列表一頁中展示多少條數(shù)據(jù)ordering = 'create_time'#指定這個(gè)列表的排序方式page_kwarg = 'p'#獲取第幾頁的數(shù)據(jù)的參數(shù)名稱def get_context_data(self, **kwargs):#get_context_data方法用于獲取上下文的數(shù)據(jù)context = super(ArticleListView, self).get_context_data(**kwargs)context["password"] = "anhuicaijingdaxue"print("="*20)print(context)print("="*20)return context在templates文件夾中創(chuàng)建模板文件book_list.html:
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>展示圖書</title> </head><body> <ul> {% for article in articles %}<li>{{ article.title }}</li>{% endfor %}</ul> </body>在book應(yīng)用的urls.py文件中,我們添加路由:
from django.urls import path from . import views from django.conf.urls import includeurlpatterns = [path('add_book/', views.add_book),path('book_list/', views.ArticleListView.as_view()), ]現(xiàn)在,我們向http://127.0.0.1:8000/book/add_book/發(fā)起請(qǐng)求:
再看看數(shù)據(jù)庫中的book_list表,可以看到表內(nèi)已經(jīng)填充了數(shù)據(jù):
向http://127.0.0.1:8000/book/book_list/發(fā)起請(qǐng)求:
向http://127.0.0.1:8000/book/book_list/?p=3發(fā)起請(qǐng)求:
現(xiàn)在,我們更改一下ArticleListView類,增加get_queryset方法,限制數(shù)據(jù)返回的條數(shù):
class ArticleListView(ListView):model = Articletemplate_name = "book_list.html"context_object_name = "articles"#在模板文件中的名字paginate_by = 10ordering = 'create_time'page_kwarg = 'p'def get_context_data(self, **kwargs):context = super(ArticleListView, self).get_context_data(**kwargs)context["password"] = "anhuicaijingdaxue"print("="*20)print(context)print("="*20)return contextdef get_queryset(self):return Article.objects.filter(id__lte = 5)向http://127.0.0.1:8000/book/book_list/發(fā)起請(qǐng)求:
Paginator和Page類
Paginator和Page類都是用來做分頁的。他們?cè)贒jango中的路徑為django.core.paginator.Paginator和django.core.paginator.Page。
上面的例子中,我們?cè)贏rticleListView類的get_context_data方法中打印了context,現(xiàn)在,我們來看一下context的輸出結(jié)果:
{'paginator': <django.core.paginator.Paginator object at 0x0000009479522FD0>, 'page_obj': <Page 1 of 1>, 'is_paginated': False, 'object_list': <QuerySet [<Article: Articl e object (1)>, <Article: Article object (2)>, <Article: Article object (3)>, <Article: Article object (4)>, <Article: Article object (5)>]>, 'articles': <QuerySet [<Article: Article object (1)>, <Article: Article object (2)>, <Article: Article object (3)>, <Article: Article object (4)>, <Article: Article object (5)>]>, 'view': <book.views.ArticleListView object at 0x000000947954D550>, 'password': 'anhuicaijingdaxue'}可以看到context的輸出結(jié)果中有一個(gè)key為paginator,它所對(duì)應(yīng)的value就是Paginator類的對(duì)象,還有一個(gè)key為page_obj,它所對(duì)應(yīng)的value為Page類的對(duì)象。
Paginator常用屬性
| count屬性 | 總共有多少條數(shù)據(jù) |
| num_pages屬性 | 總共有多少頁 |
| page_range屬性 | 頁面的區(qū)間,比如有3頁,那么返回值就是range(1,4) |
Page常用屬性和方法
| has_next方法 | 是否還有下一頁 |
| has_previous方法 | 是否還有上一頁 |
| next_page_number方法 | 下一頁的頁碼 |
| previous_page_number方法 | 上一頁的頁碼 |
| number屬性 | 當(dāng)前頁 |
| start_index方法 | 當(dāng)前這一頁的第一條數(shù)據(jù)的索引值 |
| end_index方法 | 當(dāng)前這一頁的最后一條數(shù)據(jù)的索引值 |
舉個(gè)例子
在book應(yīng)用的views.py文件中,我們重新定義ArticleListView類,并在get_context_data方法中,調(diào)用Paginator和Page類對(duì)象的屬性和方法:
class ArticleListView(ListView):model = Articletemplate_name = "book_list.html"context_object_name = "articles"#在模板文件中的名字paginate_by = 10ordering = 'create_time'page_kwarg = 'p'def get_context_data(self, **kwargs):context = super(ArticleListView, self).get_context_data(**kwargs)paginator = context.get("paginator")page_obj = context.get("page_obj")print("數(shù)據(jù)條數(shù):{}, 頁數(shù):{}, 頁面區(qū)間:{} ".format(paginator.count, paginator.num_pages, paginator.page_range))print("當(dāng)前頁:", page_obj.number)print("當(dāng)前這一頁的第一條數(shù)據(jù)的索引值:", page_obj.start_index())return contextdef get_queryset(self):return Article.objects.all()向http://127.0.0.1:8000/book/book_list/?p=2發(fā)起請(qǐng)求:
查看cmd中的輸出:
數(shù)據(jù)條數(shù):102, 頁數(shù):11, 頁面區(qū)間:range(1, 12) 當(dāng)前頁: 2 當(dāng)前這一頁的第一條數(shù)據(jù)的索引值: 11總結(jié)
以上是生活随笔為你收集整理的Django从理论到实战(part47)--ListView类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安徽的蒿子粑粑怎么做
- 下一篇: 第三次学JAVA再学不好就吃翔(part