将list_filter的可能过滤器限制为非空过滤器

时间:2011-03-18 21:11:50

标签: django django-admin

我有一个模特:

class Foo(models.Model):
   attribute = models.IntegerField()
   user = models.ForeignKey(user)

和模特管理员:

class FooAdmin(admin.ModelAdmin):
   list_filter = ('attribute',)

在admin中,我只显示活动用户的Foo对象,但属性过滤器为我提供了所有可能的属性,即使是那些不为该用户返回任何对象的属性。最后,我有很多不同的过滤器值,其中大多数对用户来说都是无用的。如何将这些过滤器值限制为与用户匹配的过滤器值。

希望这是可以理解的

干杯

解决方案: 在您的应用的admin.py中:

from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec
from django.contrib.auth.models import User
from sets import Set

class CustomChoiceFilterSpec(ChoicesFilterSpec):

    def __init__(self, f, request, params, model, model_admin):
        super(CustomChoiceFilterSpec, self).__init__(f, request, params, model,
                                                   model_admin)
    self.lookup_kwarg = '%s__attribute__exact' % f.name
    self.lookup_val = request.GET.get(self.lookup_kwarg, None)
    self.objects = list(Set([i.attribute for i in model.objects.filter(foo__user = request.user)])) # This is the magic line :) !

    def choices(self, cl):
        yield {'selected': self.lookup_val is None,
                'query_string': cl.get_query_string({}, [self.lookup_kwarg]),
                'display': ('All')}
        for val in self.objects:
            yield {'selected': smart_unicode(val) == self.lookup_val,
                    'query_string': cl.get_query_string({self.lookup_kwarg: val.attribute}),
                    'display': val.attribute}

    def title(self):
        return "Attribute"
FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'compact_filter', False), CustomChoiceFilterSpec)) 

最后一行说这种类型的过滤器仅适用于以'compact_filter'作为属性的对象。

所以我们输入了我们的模型Foo(models.py):

attribute.compact_filter = True

2 个答案:

答案 0 :(得分:1)

不幸的是,覆盖那些list_filters并不容易。

正如您在此故障单上看到的那样,编写我们自己的列表过滤器取得了巨大进步:http://code.djangoproject.com/ticket/5833但不会用于1.3。

我可以建议的是开始使用这个新的词汇表:“FilterSpec”来查找各种人的代码片段,这些代码片段能够让他们的自定义FilterSpecs在SO和google上工作。

Custom Filter in Django Admin on Django 1.3 or below
http://djangosnippets.org/snippets/1051/

我将以此为契机,自己搞乱FilterSpecs!

答案 1 :(得分:0)

list_filter = ['attribute_1', 'attribute_2']

设置管理员

的过滤器

list_display = ('attribute_1', 'attribute_2')

设置要在特定模型的管理视图表中显示的属性。

如果输入正确,我确定您已经尝试重新启动本地开发服务器和/或apache,具体取决于您是在本地开发应用程序还是直接在服务器上开发应用程序。对代码文件的更改只会在重新编译后生效,这在文件导入或直接调用时会发生。如果您尚未重新启动服务器,则该文件可能尚未重新编译,因此可能未进行更改。

我确定你已经在模型文件中编写了模型,并在admin.py文件中编写了管理过滤器?