Skip to content

Instantly share code, notes, and snippets.

@pije76
Forked from mirskiy/RelatedFieldListFilter.txt
Created August 20, 2020 23:31
Show Gist options
  • Save pije76/e92115382d44033087008a25a72cff25 to your computer and use it in GitHub Desktop.
Save pije76/e92115382d44033087008a25a72cff25 to your computer and use it in GitHub Desktop.
RelatedFieldListFilter vs RelatedOnlyFieldListFilter
from the source:
class RelatedOnlyFieldListFilter(RelatedFieldListFilter):
def field_choices(self, field, request, model_admin):
pk_qs = model_admin.get_queryset(request).distinct().values_list('%s__pk' % self.field_path, flat=True)
return field.get_choices(include_blank=False, limit_choices_to={'pk__in': pk_qs})
ex if:
class Author(models.Model):
country = models.ForeignKey('Country')
RelatedFieldListFilter will show ALL countries.
RelatedOnlyFieldListFilter will only show countries that have at least 1 Author assigned to them
NOTE: (this took me some googling, wish it were more apparent in the docs)
Filters will only show up in the side bar if there is more than one option.
So, for the example above, if RelatedOnlyFieldListFilter were used,
there would need to be an author in at least two countries before the filter showed up in the sidebar.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment