How to add methods to customised search_fields in Django admin.ModelAdmin

788 views Asked by At

I"m trying to add search option to my django admin page. Please look at the code below.

class ApplicationAdmin(admin.ModelAdmin):

def get_name(self, obj):
    return obj.user.first_name + ' ' + obj.user.last_name
list_display = ('get_name', ... ... )
#search_fields = ['first_name', 'last_name'
search_fields = ['get_name']

This implementation returns FieldError, as it seems that the search_fields attribute is unable to take the method 'get_name' as an element.

Is there a way to make search_fields take 'get_name' method as an element?

1

There are 1 answers

0
Brandon Taylor On

Django is not able to search on properties as you've discovered. However, you can simply add the first_name and last_name fields to your search_fields and it will work as expected.

If you're needing to do exact matching on the entire name value, my recommendation would be to add a denormalized field, perhaps called full_name that is kept in sync via a post_save signal.