您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Django中ListView如何使用,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guā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
怎么實(shí)現(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í)間倒序返回?cái)?shù)據(jù)
return UserProfile.objects.filter(is_deleted=False).order_by('-create_time')
如果你要對數(shù)據(jù)做更多維度的過濾,比如:既要用戶是某部門的,還只要獲取到性別是男的,這時(shí)候,可以使用 Django 提供的 Q 函數(shù)來實(shí)現(xiàn)。
我想要返回給 Template 的數(shù)據(jù)需要多個,不僅僅是user_list
,可能還有其他數(shù)據(jù),如獲取當(dāng)前登陸用戶的詳細(xì)信息,這時(shí)怎么操作?,代碼如下:
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 頁面時(shí),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'] # 加上這一行,告知允許那種請求方式
關(guān)于Django中ListView如何使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。