Django的ListView超詳細(xì)用法(含分頁(yè)paginate)
開(kāi)發(fā)環(huán)境:
python 3.6 django 1.11場(chǎng)景一
經(jīng)常有從數(shù)據(jù)庫(kù)中獲取一批數(shù)據(jù),然后在前端以列表的形式展現(xiàn),比如:獲取到所有的用戶(hù),然后在用戶(hù)列表頁(yè)面展示。
解決方案
常規(guī)寫(xiě)法是,我們通過(guò)Django的ORM查詢(xún)到所有的數(shù)據(jù),然后展示出來(lái),代碼如下:
def user_list(request): '''返回UserProfile中所有的用戶(hù)''' users = UserProfile.objects.all() return render(request, ’talks/users_list.html’, context={'user_list': users})
這樣能夠解決問(wèn)題,但是Django針對(duì)這種常用場(chǎng)景,提供了一個(gè)更快速便捷的方式,那就是ListView,用法如下:
from django.views.generic import ListViewclass UsersView(ListView): model = UserProfile template_name = ’talks/users_list.html’ context_object_name = ’user_list’
這樣我們就完成了上邊功能,代碼很簡(jiǎn)潔。
場(chǎng)景二:
我想要對(duì)數(shù)據(jù)做過(guò)濾,ListView怎么實(shí)現(xiàn)?代碼如下:
from django.views.generic import ListViewclass UsersView(ListView): model = UserProfile template_name = ’talks/users_list.html’ context_object_name = ’user_list’ def get_queryset(self): # 重寫(xiě)get_queryset方法 # 獲取所有is_deleted為False的用戶(hù),并且以時(shí)間倒序返回?cái)?shù)據(jù) return UserProfile.objects.filter(is_deleted=False).order_by(’-create_time’)
如果你要對(duì)數(shù)據(jù)做更多維度的過(guò)濾,比如:既要用戶(hù)是某部門(mén)的,還只要獲取到性別是男的,這時(shí)候,可以使用Django提供的Q函數(shù)來(lái)實(shí)現(xiàn)。
場(chǎng)景三
我想要返回給Template的數(shù)據(jù)需要多個(gè),不僅僅是user_list,可能還有其他數(shù)據(jù),如獲取當(dāng)前登陸用戶(hù)的詳細(xì)信息,這時(shí)怎么操作?,代碼如下:
from django.views.generic import ListViewclass UsersView(ListView): model = UserProfile template_name = ’talks/users_list.html’ context_object_name = ’user_list’ def get_context_data(self, **kwargs): # 重寫(xiě)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頁(yè)面時(shí),context包含為{’user_list’: user_list, ’user’: user}。
場(chǎng)景四
我想要限制接口的請(qǐng)求方式,比如限制只能GET訪問(wèn),代碼如下:
from django.views.generic import ListViewclass UsersView(ListView): model = UserProfile template_name = ’talks/users_list.html’ context_object_name = ’user_list’ http_method_names = [’GET’] # 加上這一行,告知允許那種請(qǐng)求方式
場(chǎng)景五
我卡卡卡的返回了所有的數(shù)據(jù)給前端頁(yè)面,前頁(yè)面最好得分頁(yè)展示呀,這怎么搞?
到此這篇關(guān)于Django的ListView超詳細(xì)用法(含分頁(yè)paginate)的文章就介紹到這了,更多相關(guān)Django的ListView用法內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. SSM框架JSP使用Layui實(shí)現(xiàn)layer彈出層效果2. IntelliJ IDEA導(dǎo)入jar包的方法3. 刪除docker里建立容器的操作方法4. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法5. IDEA調(diào)試源碼小技巧之辨別抽象類(lèi)或接口多種實(shí)現(xiàn)類(lèi)的正確路徑6. Django實(shí)現(xiàn)將views.py中的數(shù)據(jù)傳遞到前端html頁(yè)面,并展示7. Jquery使用原生AJAX方法請(qǐng)求數(shù)據(jù)8. JS如何在數(shù)組指定位置插入元素9. Java源碼解析之ClassLoader10. PHP下對(duì)緩沖區(qū)的控制
