1. Filtering allows searching for certain record(s) based on given criteria. According to Django Rest API Framework documentation:
The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset.
The simplest way to filter the queryset of any view that subclasses GenericAPIView
is to override the .get_queryset()
method.
Overriding this method allows you to customize the queryset returned by the view in a number of different ways.
2. Install the library for Django Filter, go here. Go for the the latest version.
3. Register your Django package in SETTINGS.PY
4. To set the GLOBAL FILTER, do this just like how you did the GLOBAL PAGINATION.
5. Update our API\VIEWS.PY:
* You need to type the exact keyword to find an exact match, so this is a case-sensitive filter. To solve this, we use custom filters instead.
6. To allow for case-insensitive filter, create a new file FILTERS.PY in the EMPLOYEES app or you can have this in API folder.
7. Then update our VIEWS.PY. Import the class EmployeeFilter from the Employees\Filters.py
To use the new filter class:
8. Now even if we search without minding the lowercase or uppercase, we can still find the record:
9. To add filters like by name and ID, we update our FILTERS.PY :
If we add the 2 filter keywords, we search the record for these 2 criteria.
10. To retrieve the employee records within the given ID range for example: PK or ID 5 - 10:
We update our FILTERS.PY as:
11. But to use the EMP_ID (ex. EMP005-EMP008) with CharField as our range filter, we update the FILTERS.PY as:
Before the Filter by Emp_ID:
After:
No PDF file attached.