Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Mufaddal1125/9a1b0a4372ce908b5889049a41faa16d to your computer and use it in GitHub Desktop.
Save Mufaddal1125/9a1b0a4372ce908b5889049a41faa16d to your computer and use it in GitHub Desktop.
Django admin custom filter that limits the choices for related fields to only those related to the current queryset, based on active filters and search terms. This ensures that dropdowns only show relevant options, improving usability for large datasets.
class LimitedChoiceRelatedListFilter(admin.RelatedOnlyFieldListFilter):
def field_choices(self, field, request, model_admin):
qs = model_admin.get_queryset(request)
for param, value in request.GET.items():
# ignore reserved keywords
if param in ["o", "e", "q"]:
continue
if value:
qs = qs.filter(**{param: value})
# also filter for search
if "q" in request.GET:
qs, _ = model_admin.get_search_results(request, qs, request.GET.get("q", ""))
pk_qs = qs.distinct().values_list(f"{self.field_path}__pk", flat=True)
return field.get_choices(include_blank=True, limit_choices_to={"pk__in": pk_qs})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment