You can modify autocomplete queryset just by overriding get_search_results like this:
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(field_name='foo')
return queryset, use_distinct
This function is inside admin.py and use it with model you refer to, if model used in autocomplete is Bar, then get_search_results should be in class BarAdmin(admin.ModelAdmin)
Also if you use same Model in multiple autocomplete_fields you can change queryset depending on where it's called. Example:
@admin.register(Foo)
class FooAdmin(admin.ModelAdmin):
fields = (
'the_field',
)
autocomplete_fields = ('the_field',)
@admin.register(Bar)
class BarAdmin(admin.ModelAdmin):
fields = (
'the_same_field',
)
autocomplete_fields = ('the_same_field',)
@admin.register(Key)
class KeyAdmin(admin.ModelAdmin):
fields = (
'name',
)
ordering = [
'-id',
]
search_fields = [
'name',
]
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:
if 'foo' in request.headers['referer']:
queryset = queryset.exclude(name='foo')
elif 'bar' in request.headers['referer']:
queryset = queryset.exclude(name='bar')
return queryset, use_distinct
We got Foo and Bar models with ForeingKeys to Key Model and used with autocomplete.
Now when we open autocomplete changing Foo, we will only see queryset with name equal to 'foo', also when we open autocomplete in Bar, we will only see queryset with name equal to 'bar', this way you can modify queryset depending on where is autocomplete called.