Member-only story
How To Make Search Fields Dynamic in the Django REST Framework
Set search fields using the query parameter

The Django REST framework provides search functionality out of the box.
Search can be accomplished by following three steps:
- Setting
search_fields
in the class - Setting
filter_backends
in the class - Sending
search
query parameter in the request
search
specifies the pattern that needs to be matched. search_fields
specify the database columns against which the pattern needs to be matched.
DRF default behavior works with static search_fields
.
In this piece, we discuss the limitations of static search_fields
and how to make search_fields
dynamic.
Usefulness
Dynamic searching ability in the back end will allow users to perform more granular searches.
This will come in handy in a scenario where your front end lists all the fields/columns of the model and allows users to select the fields against which the pattern should be matched.
Users will also have the ability to choose the matching type. Users can choose LIKE
matching, exact
matching, or starts with
matching.