Django从理论到实战(part47)--ListView类
學習筆記,僅供參考,有錯必糾
參考自:Django打造大型企業官網–Huang Y;
文章目錄
- 類視圖
- ListView類
- 舉個例子
- Paginator和Page類
- Paginator常用屬性
- Page常用屬性和方法
- 舉個例子
類視圖
ListView類
在網站開發中,經常會出現需要列出某個表中的一些數據作為列表展示出來,在Django中可以使用ListView類來幫我們快速實現這種需求。
舉個例子
首先,我們創建一個book應用,并對該APP在settings.py中進行配置:
python manage.py startapp book在book應用的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)進行遷移操作:
python manage.py makemigrations python manage.py migrate我們用Navicat連接sqlite數據庫:
打開數據庫連接,并打開庫,可以看到存在book_article表:
現在,我們在book應用的views.py文件中創建視圖函數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 = "標題: %s" % x, content = "內容:%s" % x)articles.append(article)Article.objects.bulk_create(articles)return HttpResponse("<h2>Are you OK?</h2>")在book應用的views.py文件中創建ArticleListView類,它繼承自ListView類:
class ArticleListView(ListView):model = Article#重寫model類屬性,指定這個列表是給哪個模型的template_name = "book_list.html"#指定這個列表的模板context_object_name = "articles"#在模板文件中的名字paginate_by = 10#指定這個列表一頁中展示多少條數據ordering = 'create_time'#指定這個列表的排序方式page_kwarg = 'p'#獲取第幾頁的數據的參數名稱def get_context_data(self, **kwargs):#get_context_data方法用于獲取上下文的數據context = super(ArticleListView, self).get_context_data(**kwargs)context["password"] = "anhuicaijingdaxue"print("="*20)print(context)print("="*20)return context在templates文件夾中創建模板文件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應用的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()), ]現在,我們向http://127.0.0.1:8000/book/add_book/發起請求:
再看看數據庫中的book_list表,可以看到表內已經填充了數據:
向http://127.0.0.1:8000/book/book_list/發起請求:
向http://127.0.0.1:8000/book/book_list/?p=3發起請求:
現在,我們更改一下ArticleListView類,增加get_queryset方法,限制數據返回的條數:
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/發起請求:
Paginator和Page類
Paginator和Page類都是用來做分頁的。他們在Django中的路徑為django.core.paginator.Paginator和django.core.paginator.Page。
上面的例子中,我們在ArticleListView類的get_context_data方法中打印了context,現在,我們來看一下context的輸出結果:
{'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的輸出結果中有一個key為paginator,它所對應的value就是Paginator類的對象,還有一個key為page_obj,它所對應的value為Page類的對象。
Paginator常用屬性
| count屬性 | 總共有多少條數據 |
| num_pages屬性 | 總共有多少頁 |
| page_range屬性 | 頁面的區間,比如有3頁,那么返回值就是range(1,4) |
Page常用屬性和方法
| has_next方法 | 是否還有下一頁 |
| has_previous方法 | 是否還有上一頁 |
| next_page_number方法 | 下一頁的頁碼 |
| previous_page_number方法 | 上一頁的頁碼 |
| number屬性 | 當前頁 |
| start_index方法 | 當前這一頁的第一條數據的索引值 |
| end_index方法 | 當前這一頁的最后一條數據的索引值 |
舉個例子
在book應用的views.py文件中,我們重新定義ArticleListView類,并在get_context_data方法中,調用Paginator和Page類對象的屬性和方法:
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("數據條數:{}, 頁數:{}, 頁面區間:{} ".format(paginator.count, paginator.num_pages, paginator.page_range))print("當前頁:", page_obj.number)print("當前這一頁的第一條數據的索引值:", page_obj.start_index())return contextdef get_queryset(self):return Article.objects.all()向http://127.0.0.1:8000/book/book_list/?p=2發起請求:
查看cmd中的輸出:
數據條數:102, 頁數:11, 頁面區間:range(1, 12) 當前頁: 2 當前這一頁的第一條數據的索引值: 11總結
以上是生活随笔為你收集整理的Django从理论到实战(part47)--ListView类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安徽的蒿子粑粑怎么做
- 下一篇: 斗士殿堂多少级升阶