开发者

Django Admin Filtering List By TextField

开发者 https://www.devze.com 2023-03-31 08:03 出处:网络
I need to filter an admin list based on a TextField. I want to be able to filter the queryset for all objects whose TextField value is Null.

I need to filter an admin list based on a TextField. I want to be able to filter the queryset for all objects whose TextField value is Null.

I tried the following:

 def filter_for_field(self, request, queryset):

    queryset=queryset.exclude(field__isnull=True)
    return quer开发者_高级运维yset

I added that as a method to my AdminModel and then added the property "actions=['filter_for_field'].

I also tried to do it without a return statement, no dice. The action is showing up in the admin but it is not removing objects with a null value for the TextField.

What am I doing wrong?

Is there a better way to do this?


You can use the custom FilterSpec functionality to create custom admin filter. It is available in the SVN version of Django right now and planned for Django 1.4.

from django.contrib.admin import SimpleListFilter

class IsNullFilter(SimpleListFilter):
   # Human-readable title which will be displayed in the
   # right admin sidebar just above the filter options.
   title = _('Custom filter')

   # Parameter for the filter that will be used in the URL query.
   parameter_name = 'custom_filter'

   def lookups(self, request, model_admin):
       """
       Returns a list of tuples. The first element in each
       tuple is the coded value for the option that will
       appear in the URL query. The second element is the
       human-readable name for the option that will appear
       in the right sidebar.
       """
       return (
           ('True', _('is Null')),
           ('False', _('is not Null')),
       )

   def queryset(self, request, queryset):
       """
       Returns the filtered queryset based on the value
       provided in the query string and retrievable via
       `self.value()`.
       """

       if self.value() == 'True':
           return queryset.filter(costomfield__isnull=True)
       if self.value() == 'True':
           return queryset.filter(costomfield__isnull=False)

Then you need to pass it in ModelAdmin.list_filter:

class CustomModelAdmin(admin.ModelAdmin):
    list_filter = (IsNullFilter,)
0

精彩评论

暂无评论...
验证码 换一张
取 消