Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit the queryset of autocomplete fields in Django

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?

like image 721
Benjamin Avatar asked Nov 15 '18 14:11

Benjamin


1 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.

like image 103
wanaryytel Avatar answered Sep 21 '22 08:09

wanaryytel