Adding Search to the List Screen
00:00 Adding Search to the List Screen.
00:04
Filters aren’t the only way to reduce the amount of data onscreen. Django admin also supports searching through the search_fields
option, which adds a search box to the screen.
00:15
You set it with a tuple containing the names of fields to be used for constructing a search query in the database. Anything the user types in the search box is used in an OR
clause of the fields filtering the QuerySet
. By default, each search parameter is surrounded by percent signs (%
), meaning that if you search for r
, then any word with an r
inside will appear in the results.
00:39
You can be more precise by specifying a dunder (__
) modifier on the search field.
00:45
Here you can see core/admin.py
is being edited to change this. In this code, searching is based on last_name
. The __startswith
modifier restricts the search to last names that begin with the search parameter. Searching on R
provides the following results.
01:07
Whenever a search is performed on a change list page, the Django admin calls your admin.ModelAdmin
object’s get_search_results()
method.
01:16
It returns a QuerySet
with the search results. You can fine-tune searches by overloading the method and changing the QuerySet
.
01:25 More details can be found in the documentation. Customization of the admin interface isn’t limited to how existing data is presented. It’s also possible to change how data is created and edited, and that’s what’s covered in the next section.
Become a Member to join the conversation.