5
votes

On a model admin object I have a callable function, that returns either True or False. I want to be able to use this callable to filter what is displayed in the list (i.e. list_filter). However the below code wouldn't work, because you can only use list_filter on fields:

...

class FooAdmin(admin.ModelAdmin):
    ...
    list_filter['bar']
    def bar(self, obj):
        x = ... #something boolean
        return x
...


Is there any way to use a True/False callable to filter a list in admin? Or do you have to denormalize your data if you want this functionality?

I notice that in the development docs, this is now possible: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter

However in the 1.3 docs (the Django version I'm using) it does not mention of this: https://docs.djangoproject.com/en/1.3/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_filter So I'm assuming I can't use the new functionality with my project :-(

1
I guess a follow up question to this is when will Django 1.4 be released? If it's relatively soon (i.e. less than 6 weeks) then I can use the new list_filter API :) - Jon Cox
It'll be released when it's released. Unfortunately, Django doesn't have a set release schedule. However, from what I've seen, it looks like it's close. - Chris Pratt
The dev documentation doesn't say that you can use a callable as a list_filter. - tback
@TillBackhaus in the dev version you can create a class that is used in the filter, and assign this to your model in the ModelAdmin - "a class inheriting from django.contrib.admin.SimpleListFilter, which you need to provide the title and parameter_name attributes to and override the lookups and queryset methods" - Burhan Khalid
@burhan yes, that allows quite complex filters. It however doesn't allow to use a callable as criteria like Jonathan described in the question. - tback

1 Answers

2
votes

If you can somehow express the operation of your bar function in terms of ORM double-underscore lookup paths then you may be able to create a FilterSpec in Django 1.3

See django.contrib.admin.filterspecs

These classes handle generating a list of filter choices and preparing the querystring value for the url etc. As far as I can tell they work by providing a field_path attribute which other parts of the admin code use to filter the changelist queryset.

For an example of a custom FilterSpec see:
http://djangosnippets.org/snippets/2644/