感谢gpilotino为我提供了实现正确方向的推动力。
我注意到该问题的代码正在使用datetime来确定其生效时间。因此,我使用了DateFieldFilterSpec并将其子类化。
from django.db import modelsfrom django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec,DateFieldFilterSpecfrom django.utils.encoding import smart_uniprefrom django.utils.translation import ugettext as _from datetime import datetimeclass IsLiveFilterSpec(DateFieldFilterSpec): """ Adds filtering by future and previous values in the admin filter sidebar. Set the is_live_filter filter in the model field attribute 'is_live_filter'. my_model_field.is_live_filter = True """ def __init__(self, f, request, params, model, model_admin): super(IsLiveFilterSpec, self).__init__(f, request, params, model, model_admin) today = datetime.now() self.links = ( (_('Any'), {}), (_('Yes'), {'%s__lte' % self.field.name: str(today), }), (_('No'), {'%s__gte' % self.field.name: str(today), }), ) def title(self): return "Is Live"# registering the filterFilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_live_filter', False), IsLiveFilterSpec))
要使用它,你可以将上面的代码放入filters.py中,并将其导入要添加过滤器的模型中
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)