farhan0581 / django-admin-autocomplete-filter

A simple Django app to render list filters in django admin using autocomplete widget.
GNU General Public License v3.0
351 stars 76 forks source link

Custom lookup gets ignored #95

Open lguariento opened 7 months ago

lguariento commented 7 months ago

Hello,

I'd like to have a lookup filled up conditionally. Here's my code:

class SchemeFilter(
    AutocompleteFilterFactory(
        'Scheme', 'scheme'
    )
):
    def lookups(self, request, model_admin):
        this_funder = request.GET.get('funder__pk__exact', '')
        if (this_funder != '' and Scheme.objects.filter(funders__pk__exact=this_funder).count() > 0):
            schemes= Scheme.objects.filter(funders__pk__exact=this_funder).distinct()
        elif (this_funder != '' and Scheme.objects.filter(funders__pk__exact=this_funder).count() == 0):
            schemes = Scheme.objects.none()
        else:
            schemes = Scheme.objects.all()

        return schemes.values('pk', 'name')

    def queryset(self, request, queryset):

        if self.value():
            queryset = queryset.filter(scheme__pk__exact=self.value()).distinct()

        return super().queryset(request, queryset)

This works with Django's native SimpleListFilter:

class TestSchemeFilter(admin.SimpleListFilter):

    title = 'Test Scheme'
    parameter_name = 'scheme'

    def lookups(self, request, model_admin):
        pk = request.GET.get('funder__pk__exact', '')
        if pk and Scheme.objects.filter(funders__pk__exact=pk).count() > 0:
            schemes = Scheme.objects.filter(funders__id__exact=pk)
        else:
            schemes = Scheme.objects.all()
        return [(s.id, s.name) for s in schemes]

    def queryset(self, request, queryset):

        if self.value():
            queryset = queryset.filter(scheme__pk__exact=self.value()).distinct()

PS: it looks like any customisation of the lookup gets ignored. Even something like this:

    def lookups(self, request, model_admin):
        return None

will still populate the dropdown with the full list.

Django 5.0.2, Python 3.11.