dArignac
dArignac

Reputation: 1209

Django adminsite customize search_fields query

In the django admin you can set the search_fields for the ModelAdmin to be able to search over the properties given there. My model class has a property that is not a real model property, means it is not within the database table. The property relates to another database table that is not tied to the current model through relations. But I want to be able to search over it, so I have to somehow customize the query the admin site creates to do the filtering when the search field was filled - is this possible and if, how? I can query the database table of my custom property and it then returns the ids of the model classes fitting the search. This then, as I said, has to flow into the admin site search query.

Thanks!

Upvotes: 22

Views: 24303

Answers (3)

shahjapan
shahjapan

Reputation: 14335

this might can help

search_fields = ['foreign_key__related_fieldname']

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields

Upvotes: -2

luc
luc

Reputation: 43096

Since django 1.6, you can customize the search by defining a get_search_results method in your ModelAdmin subclass.

It is well explained in django documentation. The following example is copied from this doc.

class PersonAdmin(admin.ModelAdmin):
    list_display = ('name', 'age')
    search_fields = ('name',)

    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(PersonAdmin, self).get_search_results(request, queryset, search_term)
        try:
            search_term_as_int = int(search_term)
            queryset |= self.model.objects.filter(age=search_term_as_int)
        except:
            pass
        return queryset, use_distinct

Upvotes: 32

Kozet
Kozet

Reputation: 1143

You should use search_fields = ['foreign_key__related_fieldname'] like search_fields = ['user__email'] in the admin class that extends admin.ModelAdmin

read more here

Upvotes: -1

Related Questions