Search code examples
djangodjango-modelsdjango-admin

Add filters to autocomplete fields in django


I have a question about autocomplete fields in django.

Let's assume we have these 2 models:

class Animal:     
    name = models.CharField()     
    is_big = models.BooleanField()  

class Human:     
    pet = models.ForeignKey(Animal)

And then we have the admin file which looks something like this:

class HumanAdmin(admin.ModelAdmin):
    autocomplete_fields = ['pet']

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == 'pet':
            kwargs["queryset"] = Animal.objects.filter(is_big=True)
    return super().formfield_for_foreignkey(db_field, request, **kwargs)

class AnimalAdmin(admin.ModelAdmin):
    search_fields = ['name']

admin.site.register(Animal, AnimalAdmin)
admin.site.register(Human, HumanAdmin)

What I wanted to achieve here is to have in the animal selection dropdown only the big animals which worked, and then I decided to make that filed an autocomplete one but after making it autocomplete it seems to be ignoring my formfield_for_foreignkey filter, it is now loading all the animals.

And I wanna ask how should I combine these two properly? I want an autocomplete field for animals, but I want it to consider only those who have is_big == True .

My idea is that I should somehow capture what is entered on the autocomplete textfield and add that to my filtering but I'm not sure how to do that.


Solution

  • Try to override get_search_result inside AnimalAdmin

    class AnimalAdmin(admin.ModelAdmin):
        search_fields = ['name']
    
        def get_search_results(self, request, queryset, search_term):
            queryset, use_distinct = super().get_search_results(
                request,
                queryset,
                search_term,
            )
            queryset = queryset.filter(is_big=True)
    
            return queryset, use_distinct