欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2019年08月21日 09:57:22   作者:kkevinyang  
今天小編就為大家分享一篇擴(kuò)展Django admin的list_filter()可使用范圍方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

需求描述

有時(shí)候我們會(huì)基于已有數(shù)據(jù)生成一列在表格中,類似于下面的

class BaseSchema(models.Model):
 ...
 def test_status(self):
 # pdb.set_trace()
 if datetime.date.today() < self.test_start_date:
  return '未到測(cè)試區(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">進(jìn)行中</p>')

 test_status.short_description = u'測(cè)試狀態(tài)'

但同時(shí)我們也希望可以對(duì)這一列進(jìn)行篩選,按常規(guī)的話也就是添加到list_filter中:

list_filter = ('test_status')

這時(shí)候我們會(huì)看到django的溫馨報(bào)錯(cuò):

The value of 'list_filter[0]' refers to 'test_status', which does not refer to a Field. 

也就是說不能使用list_filter對(duì)非Field進(jìn)行篩選。

解決辦法

最簡單的方法

那就是把這個(gè)字段記錄進(jìn)field啊,這樣就可以用了。但是我并不想這么做

更高端的方法

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

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中是這樣實(shí)現(xiàn)的篩選的方法,那我們只要覆蓋這個(gè)方法就好了:

class StatusFilter(SimpleListFilter):
 title = 'status'
 parameter_name = 'status'

 def lookups(self, request, model_admin):
 return [(1, '已下線'), (2, '進(jìn)行中'), (3, '未到測(cè)試區(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)

然后在添加進(jìn)list_filter中:

list_filter = (StatusFilter,)

bingo!

以上這篇擴(kuò)展Django admin的list_filter()可使用范圍方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論