Django Admin Autocomplete Field Search Customization

Hi!

I have a need to customize autocomplete field on django admin.
So basically, I filter out serial numbers.
In some cases, users input numbers with preceding zeroes like this. 00001234
The actual search should be done for 1234.
So all I need is to get rid of preceding zeroes from user input.

How can I do this?

Any help would be appreciated
@KenWhitesell , any idea on this?

If you’re using the Django Admin autocomplete field for the search, it calls (among other things) the ModelAdmin method get_search_results. You could override that method in your ModelAdmin class to remove leading zeros from the search parameter.

@KenWhitesell
My fields are autocomplete_fields, not search_fields

Then I’m not following what you’re referring to here.

From autocomplete_fields -

You must define search_fields on the related object’s ModelAdmin because the autocomplete search uses it.

So in your data entry form, if you have an FK using the autocomplete field, it is calling the search on the target model.

@KenWhitesell
That makes sense. But I am not sure when the method get_search_results is called

@KenWhitesell
It is only called on list view

I just tried it out - when I go to edit an entity using an auto complete field referencing an FK-related model, that target model’s get_search_results method gets called.

Snippets:

class Blog(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Entry(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    headline = models.CharField(max_length=255)

@admin.register(Blog)
class BlogAdmin(admin.ModelAdmin):
    form = BlogForm
    search_fields = ['name']
    def get_search_results(self, request, queryset, search_term):
        print("In get search results")
        results = super().get_search_results(request, queryset, search_term)
        return results

@admin.register(Entry)
class EntryAdmin(admin.ModelAdmin):
    autocomplete_fields = ['blog']

This will print “In get search results” on the console every time a key is pressed in the ‘blog’ field when editing an Entry object.

1 Like

@KenWhitesell
Yes, you are right!

I should override that method on the target admin, not caller’s admin.
Thank you