Alex Rivera | Logout

How to override the queryset giving the filters in list_filter?

Asked 2012-09-21T00:08:36.783
29

Given the following models

class AnotherModel(models.Model):
    n = models.IntegerField()

class MyModel(models.Model):
    somefield = models.ForeignKey(AnotherModel)

and admin

class MyModelAdmin(admin.ModelAdmin):        
    list_filter = ('somefield',)

how can I filter the instances of AnotherModel to show only those with a given n value in my admin filter?

I need something like:

Filter

By somefield

all

[list of AnotherModel instances with given n]

Edit
Report

1 Answer

7

Edit - this method has been pointed out to have issues, see below

You can do it like this:

Let's say you have a model called Animal, which has a ForeignKey field to a model called Species. In a particular admin list, you want to allow only certain species to be shown in the animals filter choices.

First, specify a custom ListFilter called SpeciesFilter in the Animal's ModelAdmin:

class AnimalAdmin(ModelAdmin):
    list_filter = (('species', SpeciesFilter),)

Then define the SpeciesFilter:

from django.contrib.admin.filters import RelatedFieldListFilter

class SpeciesFilter(RelatedFieldListFilter):
    def __init__(self, field, request, *args, **kwargs):
        """Get the species you want to limit it to.
        This could be determined by the request,
        But in this example we'll just specify an
        arbitrary species"""
        species = Species.objects.get(name='Tarantula')

        #Limit the choices on the field
        field.rel.limit_choices_to = {'species': species}

        #Let the RelatedFieldListFilter do its magic 
        super(SpeciesFilter, self).__init__(field, request, *args, **kwargs)

That should do it.

answered 2013-02-18T15:58:47.317

Your Answer