Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AutocompleteListFilter Options #7

Open
Bash4195 opened this issue Jan 21, 2020 · 1 comment
Open

AutocompleteListFilter Options #7

Bash4195 opened this issue Jan 21, 2020 · 1 comment

Comments

@Bash4195
Copy link

Bash4195 commented Jan 21, 2020

Is it possible to pass filtering options to AutocompleteListFilter?

For example, I want to filter by admins and I have their role set as a field in the model, I'd just need to pass that to the filter somehow.

If this isn't possible, it'd be a great feature for the future!

@julianwachholz
Copy link
Owner

Great idea! I had a quick look and unfortunately it doesn't look like it's easily achieved.
The Django internal AutocompleteJsonView only uses search_fields defined on the model's ModelAdmin and doesn't accept any of the filtering URL parameters that are available on regular changelist views (maybe we could propose a change to Django?).

One possible workaround is overwriting the get_search_results() method on your ModelAdmin for the model you want to look up. However, this will affect your normal search on the model admin as well. To circumvent this, one can also create a proxy model and register a separate ModelAdmin just for the filtered objects:

class SuperUser(User):
    """Proxy model is only needed to register a second admin for the same model."""
    class Meta:
        proxy = True


@admin.register(SuperUser)
class SuperUserAdmin(admin.ModelAdmin):
    model = SuperUser

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        return qs.filter(is_superuser=True)

But then your model you want to filter must have a foreign key to the proxy model instead:

class MyModel(models.Model):
    # does not actually filter to only super users
    user = models.ForeignKey(to=SuperUser, on_delete=models.PROTECT)


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants