Django的ListView超詳細用法(含分頁paginate)
開發(fā)環(huán)境:
- python 3.6
- django 1.11
場景一
經(jīng)常有從數(shù)據(jù)庫中獲取一批數(shù)據(jù),然后在前端以列表的形式展現(xiàn),比如:獲取到所有的用戶,然后在用戶列表頁面展示。
解決方案
常規(guī)寫法是,我們通過Django的ORM查詢到所有的數(shù)據(jù),然后展示出來,代碼如下:
def user_list(request):
"""返回UserProfile中所有的用戶"""
users = UserProfile.objects.all()
return render(request, 'talks/users_list.html', context={"user_list": users})
這樣能夠解決問題,但是Django針對這種常用場景,提供了一個更快速便捷的方式,那就是ListView,用法如下:
from django.views.generic import ListView class UsersView(ListView): model = UserProfile template_name = 'talks/users_list.html' context_object_name = 'user_list'
這樣我們就完成了上邊功能,代碼很簡潔。
場景二:
我想要對數(shù)據(jù)做過濾,ListView怎么實現(xiàn)?代碼如下:
from django.views.generic import ListView
class UsersView(ListView):
model = UserProfile
template_name = 'talks/users_list.html'
context_object_name = 'user_list'
def get_queryset(self): # 重寫get_queryset方法
# 獲取所有is_deleted為False的用戶,并且以時間倒序返回數(shù)據(jù)
return UserProfile.objects.filter(is_deleted=False).order_by('-create_time')
如果你要對數(shù)據(jù)做更多維度的過濾,比如:既要用戶是某部門的,還只要獲取到性別是男的,這時候,可以使用Django提供的Q函數(shù)來實現(xiàn)。
場景三
我想要返回給Template的數(shù)據(jù)需要多個,不僅僅是user_list,可能還有其他數(shù)據(jù),如獲取當(dāng)前登陸用戶的詳細信息,這時怎么操作?,代碼如下:
from django.views.generic import ListView
class UsersView(ListView):
model = UserProfile
template_name = 'talks/users_list.html'
context_object_name = 'user_list'
def get_context_data(self, **kwargs): # 重寫get_context_data方法
# 很關(guān)鍵,必須把原方法的結(jié)果拿到
context = super().get_context_data(**kwargs)
username = self.request.GET.get('user', None)
context['user'] = UserProfile.objects.get(username=username
return context
這樣,你返回給Template頁面時,context包含為{'user_list': user_list, 'user': user}。
場景四
我想要限制接口的請求方式,比如限制只能GET訪問,代碼如下:
from django.views.generic import ListView class UsersView(ListView): model = UserProfile template_name = 'talks/users_list.html' context_object_name = 'user_list' http_method_names = ['GET'] # 加上這一行,告知允許那種請求方式
場景五
我卡卡卡的返回了所有的數(shù)據(jù)給前端頁面,前頁面最好得分頁展示呀,這怎么搞?
到此這篇關(guān)于Django的ListView超詳細用法(含分頁paginate)的文章就介紹到這了,更多相關(guān)Django的ListView用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題
這篇文章主要介紹了解決pycharm不能自動補全第三方庫的函數(shù)和屬性問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
Python爬蟲中urllib庫的進階學(xué)習(xí)
本篇文章主要介紹了Python爬蟲中urllib庫的進階學(xué)習(xí)內(nèi)容,對此有興趣的朋友趕緊學(xué)習(xí)分享下。2018-01-01
Python 多線程搜索txt文件的內(nèi)容,并寫入搜到的內(nèi)容(Lock)方法
今天小編就為大家分享一篇Python 多線程搜索txt文件的內(nèi)容,并寫入搜到的內(nèi)容(Lock)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-08-08
在tensorflow中實現(xiàn)去除不足一個batch的數(shù)據(jù)
今天小編就為大家分享一篇在tensorflow中實現(xiàn)去除不足一個batch的數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01
python 中不同包 類 方法 之間的調(diào)用詳解
這篇文章主要介紹了python 中不同包 類 方法 之間的調(diào)用詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03

