Following this answer , I was able to filter out the selection of foreign keys to select:

But when I mark spm as autocomplete_field:, autocomplete_fields = ['spm']the spm field goes from the selection field to the autocomplete search field:

But the choice of a foreign key is not limited, as already configured in "formfield_for_foreignkey".
Even when I attach the widget inside the formfield_for_foreignkey method, spm autocomplete options become limited:
@admin.register(CustomModel)
class CustomModelAdmin(admin.ModelAdmin):
search_fields = ['name']
def get_form(self, request, obj=None, **kwargs):
request.current_object = obj
return super(CustomModelAdmin, self).get_form(request, obj, **kwargs)
def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == 'spm':
instance = request.current_object
if instance.brand and instance.memory_size:
filtered_qs=StandardProductWithMemorySize.objects.filter(
product__brand=instance.brand,
memory_size=instance.memory_size
)
kwargs['queryset'] = filtered_qs
db = kwargs.get('using')
kwargs['widget'] = AutocompleteSelect(db_field.remote_field, self.admin_site)
return super(
CustomModelAdmin, self
).formfield_for_foreignkey(db_field, request, **kwargs)
source
share