Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin, list filter based on boolean callable

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 :-(

like image 898
Jon Cox Avatar asked Nov 05 '22 09:11

Jon Cox


1 Answers

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/

like image 121
Anentropic Avatar answered Nov 15 '22 07:11

Anentropic