亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

擴展Django admin的list_filter()可使用范圍方法

 更新時間:2019年08月21日 09:57:22   作者:kkevinyang  
今天小編就為大家分享一篇擴展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啊,這樣就可以用了。但是我并不想這么做

更高端的方法

參考https://stackoverflow.com/questions/12102697/creating-custom-filters-for-list-filter-in-django-admin/45136544#45136544第二個回答中的事例:

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)文章

最新評論