擴展Django admin的list_filter()可使用范圍方法
需求描述
有時候我們會基于已有數(shù)據(jù)生成一列在表格中,類似于下面的
class BaseSchema(models.Model): ... def test_status(self): # pdb.set_trace() if datetime.date.today() < self.test_start_date: return '未到測試區(qū)間' elif self.test_end_date and datetime.date.today() > self.test_end_date: return format_html('<p style="color: red">已下線</p>') else: return format_html('<p style="color: green">進行中</p>') test_status.short_description = u'測試狀態(tài)'
但同時我們也希望可以對這一列進行篩選,按常規(guī)的話也就是添加到list_filter中:
list_filter = ('test_status')
這時候我們會看到django的溫馨報錯:
The value of 'list_filter[0]' refers to 'test_status', which does not refer to a Field.
也就是說不能使用list_filter對非Field進行篩選。
解決辦法
最簡單的方法
那就是把這個字段記錄進field啊,這樣就可以用了。但是我并不想這么做
更高端的方法
from django.contrib.admin import SimpleListFilter class CountryFilter(SimpleListFilter): title = 'country' # or use _('country') for translated title parameter_name = 'country' def lookups(self, request, model_admin): countries = set([c.country for c in model_admin.model.objects.all()]) return [(c.id, c.name) for c in countries] + [ ('AFRICA', 'AFRICA - ALL')] def queryset(self, request, queryset): if self.value() == 'AFRICA': return queryset.filter(country__continent='Africa') if self.value(): return queryset.filter(country__id__exact=self.value()) class CityAdmin(ModelAdmin): list_filter = (CountryFilter,)
現(xiàn)在我們知道django中是這樣實現(xiàn)的篩選的方法,那我們只要覆蓋這個方法就好了:
class StatusFilter(SimpleListFilter): title = 'status' parameter_name = 'status' def lookups(self, request, model_admin): return [(1, '已下線'), (2, '進行中'), (3, '未到測試區(qū)間')] def queryset(self, request, queryset): this_day = datetime.date.today() # pdb.set_trace() if self.value() == '3': return queryset.filter(test_start_date__gt=this_day) elif self.value() == '1': return queryset.filter(test_end_date__lt=this_day) elif self.value() == '2': return queryset.filter(test_end_date__gte=this_day, test_start_date__lte=this_day)
然后在添加進list_filter中:
list_filter = (StatusFilter,)
bingo!
以上這篇擴展Django admin的list_filter()可使用范圍方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
python TK庫簡單應(yīng)用(實時顯示子進程輸出)
這篇文章主要介紹了python TK庫簡單應(yīng)用(實時顯示子進程輸出),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10tensorflow通過模型文件,使用tensorboard查看其模型圖Graph方式
今天小編就為大家分享一篇tensorflow通過模型文件,使用tensorboard查看其模型圖Graph方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01用Python做個自動化彈鋼琴腳本實現(xiàn)天空之城彈奏
突然靈機一動,能不能用Python自動化腳本彈奏一曲美妙的鋼琴曲呢?今天就一起帶大家如何用Python實現(xiàn)自動化彈出一首《天空之城》有需要的朋友可以借鑒參考下2021-09-09基于Python的微信機器人開發(fā) 微信登錄和獲取好友列表實現(xiàn)解析
這篇文章主要介紹了Python微信機器人開發(fā) 微信登錄和獲取好友列表實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08