Django的ListView超詳細用法(含分頁paginate)
阿新 • • 發佈:2020-05-21
開發環境:
- python 3.6
- django 1.11
場景一
經常有從資料庫中獲取一批資料,然後在前端以列表的形式展現,比如:獲取到所有的使用者,然後在使用者列表頁面展示。
解決方案
常規寫法是,我們通過Django的ORM查詢到所有的資料,然後展示出來,程式碼如下:
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'
這樣我們就完成了上邊功能,程式碼很簡潔。
場景二:
我想要對資料做過濾,ListView怎麼實現?程式碼如下:
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的使用者,並且以時間倒序返回資料 return UserProfile.objects.filter(is_deleted=False).order_by('-create_time')
如果你要對資料做更多維度的過濾,比如:既要使用者是某部門的,還只要獲取到性別是男的,這時候,可以使用Django提供的Q函式來實現。
場景三
我想要返回給Template的資料需要多個,不僅僅是user_list,可能還有其他資料,如獲取當前登陸使用者的詳細資訊,這時怎麼操作?,程式碼如下:
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方法 # 很關鍵,必須把原方法的結果拿到 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'] # 加上這一行,告知允許那種請求方式
場景五
我卡卡卡的返回了所有的資料給前端頁面,前頁面最好得分頁展示呀,這怎麼搞?
到此這篇關於Django的ListView超詳細用法(含分頁paginate)的文章就介紹到這了,更多相關Django的ListView用法內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!