Limit the queryset of autocomplete fields in Django

Viewed 2401

I have a ModelAdmin in Django 2.1.3 like this:

class BoxAdmin(admin.ModelAdmin):
    autocomplete_fields = ['testkit']

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'testkit':
            kwargs['queryset'] = Barcode.objects.exclude(testkit__in=Box.objects.all().values('testkit'))
        return super().formfield_for_foreignkey(db_field, request, **kwargs)

the formfield_for_foreignkey method is written for "traditional" foreign key fields. For the autocomplete field it ensures that an error is displayed when a testkit outside of the queryset is selected. It doesn't however limit the results found in the autocomplete field. The documentation does not mention any restrictions for custom querysets. This answer is related but only deals with authorization.

It is possible to override the get_search_result method of the related ModelAdmin.

class TestkitAdmin(admin.ModelAdmin):
    search_fields = ['number']

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        if 'autocomplete' in request.path:
            queryset = queryset.exclude(testkit__in=Box.objects.all().values('testkit'))
        return queryset, use_distinct

But I don't find a way to determine from which autocomplete field the search request came. Thus I can only program it to meet the needs of one referencing ModelAdmin.

How can I correctly limit the queryset of the autocomplete field?

2 Answers

You can override the Django autocomplete.js static file in static/admin/js/autocomplete.js. Django will always prefer the file you have overwritten.

Then in the overwritten file modify the djangoAdminSelect2() function something like this:

$.fn.djangoAdminSelect2 = function(options) {
    var settings = $.extend({}, options);
    $.each(this, function(i, element) {
        var $element = $(element);

        $.extend(settings, {
            'ac_field_name': $element.parents().filter('.related-widget-wrapper').find('select').attr('name')
        });

        init($element, settings);
    });
    return this;
};

and the init() function like this:

var init = function($element, options) {
    var settings = $.extend({
        ajax: {
            data: function(params) {
                return {
                    term: params.term,
                    page: params.page,
                    field_name: options.ac_field_name
                };
            }
        }
    }, options);
    $element.select2(settings);
};

Then in your get_search_results() just access the request GET parameter field_name and voila.

Of course you can make the JS look nicer, but in principle it works like this.

This question look hold but I've seen many people keep asking for it and other give very complicated answers..

Then the simplest way to limit the autocomplete list is to limit the queryset by surcharging the get_search_results or the get_queryset inside the related object’s ModelAdmin

Now to know when its called by your autocomplete field you have:

  • request.path : that will always contain 'autocomplete' string
  • request.GET.get('model_name') : model name, on your exemple its the model 'box'
  • request.GET.get('field_name') : field name, on your exemple its the field 'testkit'

Then your code should look like that:

class TestkitAdmin(admin.ModelAdmin):
    search_fields = ['number']

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super().get_search_results(request, queryset, search_term)
        if 'autocomplete' in request.path and request.GET.get('model_name') == 'box' and request.GET.get('field_name') == 'testkit':
            queryset = queryset.exclude(testkit__in=Box.objects.all().values('testkit'))
        return queryset, use_distinct
Related