How to Add Search in Django Admin: Simple Guide
To add search in Django admin, define the
search_fields attribute in your ModelAdmin class with a list of model field names you want to search. This enables a search box in the admin interface that filters results based on those fields.Syntax
The search_fields attribute is a list of strings representing the model fields to be searched in the Django admin. It is set inside a ModelAdmin subclass.
Each string can be a field name or a related field using Django ORM lookup syntax.
python
class YourModelAdmin(admin.ModelAdmin): search_fields = ['field1', 'field2', 'relatedmodel__field']
Example
This example shows how to add search functionality for a Book model by searching the title and author__name fields in the Django admin.
python
from django.contrib import admin from .models import Book class BookAdmin(admin.ModelAdmin): search_fields = ['title', 'author__name'] admin.site.register(Book, BookAdmin)
Output
In the Django admin, a search box appears on the Book list page. Typing keywords filters books by title or author name.
Common Pitfalls
- Not using
search_fieldsinside aModelAdminsubclass causes no search box to appear. - Using incorrect field names or forgetting related field syntax (double underscores) results in errors or no search results.
- Adding too many or large text fields can slow down admin search performance.
python
class WrongAdmin(admin.ModelAdmin): search_fields = ['nonexistent_field'] # This will cause an error class CorrectAdmin(admin.ModelAdmin): search_fields = ['correct_field']
Quick Reference
Summary tips for adding search in Django admin:
- Use
search_fieldsin yourModelAdminclass. - List fields as strings, including related fields with
__. - Keep searchable fields relevant and indexed for performance.
- Test search in admin after registering your model.
Key Takeaways
Add search in Django admin by setting the search_fields attribute in ModelAdmin.
Use field names or related fields with double underscores in search_fields.
Ensure fields exist and are indexed for better search performance.
Register your ModelAdmin class with the admin site to enable search.
Avoid adding too many large text fields to search_fields to keep admin fast.