applegrew / django-select2

This is a Django integration for Select2

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to add limitations to a RelatedFieldMixin

PaleNeutron opened this issue · comments

Goal
As we know,when we use default autocomplete_fields, widget, it get's result by target Admin's get_search_results method.

Problem
But when we use select2 provided Field, it will load all choice at the very beginning and just call field's limit_choices_to query. Thus, we have no way to limit result by current request info.

Code Snippet
Please provide a code snippet of your problem.

Hey @PaleNeutron,

thanks for reaching out. So what you are looking for should be possible. If I understand you correctly, you want to create a select input, where you are using the request information, like request.user to alter the select options.

This isn't possible with the current Django implementation of autocomplete_fields in fact not even limit_choices_to is. However, this patch will make it possible, to don't forget to 👍 it django/django#11026

So to make this possible, please follow the documentation and setup a regular Select2 field in the admin. The documentation should help you out. Once that is working, you need to override the filter_queryset method of your widget.

def filter_queryset(self, request, term, queryset=None, **dependent_fields):
"""
Return QuerySet filtered by search_fields matching the passed term.
Args:
request (django.http.request.HttpRequest): The request is being passed from
the JSON view and can be used to dynamically alter the response queryset.
term (str): Search term
queryset (django.db.models.query.QuerySet): QuerySet to select choices from.
**dependent_fields: Dependent fields and their values. If you want to inherit
from ModelSelect2Mixin and later call to this method, be sure to pop
everything from keyword arguments that is not a dependent field.
Returns:
QuerySet: Filtered QuerySet
"""

As you see, the method receives the request as well as the default queryset. Whatever you return in this method, will be used to render the options.

Let me know if you have any trouble.

Best
-Joe