admin.ModelAdmin.search_fields

ModelAdmin.search_fields

Set search_fields to enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box.

These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:

search_fields = ['foreign_key__related_fieldname']

For example, if you have a blog entry with an author, the following definition would enable searching blog entries by the email address of the author:

search_fields = ['user__email']

When somebody does a search in the admin search box, Django splits the search query into words and returns all objects that contain each of the words, case insensitive, where each word must be in at least one of search_fields. For example, if search_fields is set to ['first_name', 'last_name'] and a user searches for john lennon, Django will do the equivalent of this SQL WHERE clause:

WHERE (first_name ILIKE '%john%' OR last_name ILIKE '%john%')
AND (first_name ILIKE '%lennon%' OR last_name ILIKE '%lennon%')

For faster and/or more restrictive searches, prefix the field name with an operator:

^

Use the ‘^’ operator to match starting at the beginning of the field. For example, if search_fields is set to ['^first_name', '^last_name'] and a user searches for john lennon, Django will do the equivalent of this SQL WHERE clause:

WHERE (first_name ILIKE 'john%' OR last_name ILIKE 'john%')
AND (first_name ILIKE 'lennon%' OR last_name ILIKE 'lennon%')

This query is more efficient than the normal '%john%' query, because the database only needs to check the beginning of a column’s data, rather than seeking through the entire column’s data. Plus, if the column has an index on it, some databases may be able to use the index for this query, even though it’s a LIKE query.

=

Use the ‘=’ operator for case-insensitive exact matching. For example, if search_fields is set to ['=first_name', '=last_name'] and a user searches for john lennon, Django will do the equivalent of this SQL WHERE clause:

WHERE (first_name ILIKE 'john' OR last_name ILIKE 'john')
AND (first_name ILIKE 'lennon' OR last_name ILIKE 'lennon')

Note that the query input is split by spaces, so, following this example, it’s currently not possible to search for all records in which first_name is exactly 'john winston' (containing a space).

@
Using the ‘@’ operator to perform a full text match. This is like the default search method but uses an index. Currently this is only available for MySQL.

If you need to customize search you can use ModelAdmin.get_search_results() to provide additional or alternate search behavior.

doc_Django
2016-10-09 18:33:56
Comments
Leave a Comment

Please login to continue.