How to override the queryset giving the filters in list_filter?

后端 未结 4 2227
盖世英雄少女心
盖世英雄少女心 2020-12-15 18:42

Given the following models

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

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


        
4条回答
  •  春和景丽
    2020-12-15 19:07

    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.

提交回复
热议问题