这是我对 Django 1.4 的通用和可重用实现的看法,如果你碰巧卡在那个版本上。它的灵感来自现在是 Django 1.8及更高版本的一部分的内置版本。此外,将其适应 1.5-1.7 应该是一项相当小的任务,主要是查询集方法在其中更改了名称。我已将过滤器本身放在core
我拥有的应用程序中,但您显然可以将它放在任何地方。
执行:
# myproject/core/admin/filters.py:
from django.contrib.admin.filters import RelatedFieldListFilter
class RelatedOnlyFieldListFilter(RelatedFieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.request = request
self.model_admin = model_admin
super(RelatedOnlyFieldListFilter, self).__init__(field, request, params, model, model_admin, field_path)
def choices(self, cl):
limit_choices_to = set(self.model_admin.queryset(self.request).values_list(self.field.name, flat=True))
self.lookup_choices = [(pk_val, val) for pk_val, val in self.lookup_choices if pk_val in limit_choices_to]
return super(RelatedOnlyFieldListFilter, self).choices(cl)
用法:
# myapp/admin.py:
from django.contrib import admin
from myproject.core.admin.filters import RelatedOnlyFieldListFilter
from myproject.myapp.models import MyClass
class MyClassAdmin(admin.ModelAdmin):
list_filter = (
('myfield', RelatedOnlyFieldListFilter),
)
admin.site.register(MyClass, MyClassAdmin)
如果您稍后更新到 Django 1.8,您应该能够更改此导入:
from myproject.core.admin.filters import RelatedOnlyFieldListFilter
对此:
from django.contrib.admin.filters import RelatedOnlyFieldListFilter