tags:

views:

453

answers:

2

I have a Django model containing a text field. In the admin GUI, I'd like to be able to filter just those records containing text in this field. Is it possible?

Code something like this will filter on the contents of textfield, but shows filters on 'All' and each distinct entry in the filter. I'd like to filter 'All' or 'Contains something'.

class MyModel(models.Model):
    # ...
    textfield = models.CharField(max_length=100)
    # ...

class MyModelAdmin(admin.ModelAdmin):
    list_display = ('...', 'textfield', '...')
    list_filter = ('...', 'textfield', '...')
A: 

No. See http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-filter

Set list_filter to activate filters in the right sidebar of the change list page of the admin. This should be a list of field names, and each specified field should be either a BooleanField, CharField, DateField, DateTimeField, IntegerField or ForeignKey.

But...

Two things.

  1. Be sure to allow blank for your text field.

    class MyModel(models.Model): # ... textfield = models.CharField(max_length=100,blank=True) # ...

  2. Add a is_blank method to help with processing. It doesn't filter, but it's helpful.

    def is_blank(self): return len(self.textfield) == 0

S.Lott
+6  A: 

Yes, but it's not documented. Look at django\contrib\admin\filterspecs.py to see how the default filterspecs are created and how you can create your own. This feature is planned for version 1.1, and there's already a patch if you want to try the feature now on the latest HEAD revision: http://code.djangoproject.com/ticket/5833

Also not documented is the fact that you can put arbitrary GET parameters on the URL of your change_list page to filter the results. For example /admin/app/model/?field1__lte=5&field2__gte=10 Unfortunately ?field__isnull=True won't work, but you can easily experiment to see if you could find a filter that would work in your case.