溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python:Django的ListView超詳細用法(含分頁paginate功能)

發布時間:2020-08-16 17:56:38 來源:ITPUB博客 閱讀:225 作者:千鋒Python唐小強 欄目:編程語言

開發環境:

python 3.6django 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'] # 加上這一行,告知允許那種請求方式


不清楚的地方,可以留言!更多Python教程也會繼續更新!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女