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?