Search objects in Django Admin

Built-in search functionality in Django Admin

I have added a bit more products and it looks amazing, but something is missing.

image Since we have so many products we need a way to search for what we need.

Let's add a search bar.

Add search_fields to the ProductAdmin

class ProductAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}
    list_display = ('name', 'slug', 'is_active', 'id',)
    filter_horizontal = ('category',)
    search_fields = ('name',) #  new


admin.site.register(Product, ProductAdmin)

And now we have this small search bar on top of the list of products. It will search over the name field in our model.

image

But we want some more tools for finding the right item and for that we need filters.

Advanced search and custom search tools in Django Admin

For the advanced search features let's install djangoql package.

Run this command within the virtual env:

pip install djangoql==0.17.1

and add djangoql==0.17.1 to the requirements.txt

Add 'djangoql' to INSTALLED_APPS in your settings.py:

INSTALLED_APPS = [
    ...
    'djangoql',
    ...
]

Adding DjangoQLSearchMixin your model admin will replace the standard Django search functionality with DjangoQL search. DjangoQL will recognise if you have defined search_fields in your ModelAdmin class, and doing so will allow you to choose between an advanced search with DjangoQL and a standard Django search (as specified by search fields).

Example for our Product model:

from djangoql.admin import DjangoQLSearchMixin

class ProductAdmin(DjangoQLSearchMixin, admin.ModelAdmin):
    prepopulated_fields = {'slug': ('name',)}
    list_display = ('name', 'slug', 'is_active', 'id',)
    filter_horizontal = ('category',)
    search_fields = ('name',)
    list_filter = ('category', 'is_active',)


admin.site.register(Product, ProductAdmin)

image