How to override the queryset giving the filters in list_filter?

后端 未结 4 2232
盖世英雄少女心
盖世英雄少女心 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:04

    I found another method similar to @seddonym, but doesn't mess with the caching. It is based on this Django code, but uses undocumented method field_choices, which can be subject to change in the future Django releases. The code for @seddonym's case would be:

    from django.contrib.admin.filters import RelatedFieldListFilter
    
    class SpeciesFilter(RelatedFieldListFilter):
        def field_choices(self, field, request, model_admin):
            return field.get_choices(include_blank=False, limit_choices_to={'name': 'Tarantula'})
    

    Or in my case the working code is:

    from django.contrib.admin.filters import RelatedFieldListFilter
    
    class UnitFilter(RelatedFieldListFilter):
        def field_choices(self, field, request, model_admin):
            return field.get_choices(include_blank=False, limit_choices_to={'pk__in': request.user.administrated_units.all()})
    
    

提交回复
热议问题