Configuring filter backend classes

So far, we have been working with the entire queryset as the result set. For example, whenever we requested the drones resource collection, the RESTful Web Service worked with the entire resource collection and used the default sorting we had configured in the model. Now, we want our RESTful Web Service to be able to provide filtering, searching, and sorting features.

It is very important to understand that we have to be careful with the fields we configure to be available in the filtering, searching, and ordering features. The configuration will have an impact on the queries executed on the database, and therefore, we must make sure that we have the appropriate database optimizations, considering the queries that will be executed. Specific database optimizations are outside of the scope of this book, but you definitely must take them into account when you configure these features.

Make sure you quit Django's development server. Remember that you just need to press Ctrl + C in the terminal or Command Prompt window in which it is running.

Run the following command to install the django-filter package in our virtual environment. This package will enable us to use many field filtering features that we can easily customize in the Django REST framework. Make sure the virtual environment is activated, and run the following command:

    pip install django-filter

The last lines of the output will indicate that the django-filter package has been successfully installed:

     Collecting django-filter
     Downloading django_filter-1.1.0-py2.py3-none-any.whl
     Installing collected packages: django-filter
     Successfully installed django-filter-1.1.0

We will work with the following three classes:

  • rest_framework.filters.OrderingFilter: This class allows the client to control how the results are ordered with a single query parameter. We can specify which fields may be ordered against.
  • django_filters.rest_framework.DjangoFilterBackend: This class provides field filtering capabilities. We can specify the set of fields we want to be able to filter against, and the filter backend defined in the django-filter package will create a new django_filters.rest_framework.FilterSet class and associate it to the class-based view. It is also possible to create our own rest_framework.filters.FilterSet class, with more customized settings, and write our own code to associate it with the class-based view.
  • rest_framework.filters.SearchFilter: This class provides single query parameter-based searching capabilities, and its behavior is based on the Django admin's search function. We can specify the set of fields we want to include for the search feature and the client will be able to filter items by making queries that search on these fields with a single query. It is useful when we want to make it possible for a request to search on multiple fields with a single query.

It is possible to configure the filter backends by including any of the previously enumerated classes in a tuple and assigning it to the filter_backends class attribute for the generic view classes. In our RESTful Web Service, we want all our class-based views to use the same filter backends, and therefore, we will make changes in the global configuration.

Open the restful01/restful01/settings.py file that declares module-level variables that define the configuration of Django for the restful01 project. We will make some changes to this Django settings file. Add the highlighted lines that declare the 'DEFAULT_FILTER_BACKENDS' key and assign a tuple of strings as its value with the three classes we have analyzed. The following lines show the new declaration of the REST_FRAMEWORK dictionary. The code file for the sample is included in the hillar_django_restful_07_03 folder in the restful01/restful01/settings.py file:

  REST_FRAMEWORK = { 
    'DEFAULT_PAGINATION_CLASS': 
    'drones.custompagination.LimitOffsetPaginationWithUpperBound', 
    'PAGE_SIZE': 4, 
    'DEFAULT_FILTER_BACKENDS': (
        'django_filters.rest_framework.DjangoFilterBackend', 
        'rest_framework.filters.OrderingFilter', 
        'rest_framework.filters.SearchFilter', 
        ), 
  } 

Locate the lines that assign a string list to INSTALLED_APPS to declare the installed apps. Add the following string to the INSTALLED_APPS string list and save the changes to the settings.py file:

  'django_filters',

The following lines show the new code that declares the INSTALLED_APPS string list with the added line highlighted and with comments to understand what each added string means. The code file for the sample is included in the hillar_django_restful_07_03 folder in the restful01/restful01/settings.py file:

  INSTALLED_APPS = [ 
     'django.contrib.admin', 
     'django.contrib.auth', 
     'django.contrib.contenttypes', 
     'django.contrib.sessions', 
     'django.contrib.messages', 
     'django.contrib.staticfiles', 
     # Django REST Framework 
     'rest_framework', 
     # Drones application 
     'drones.apps.DronesConfig',

     # Django Filters, 
     'django_filters', 
 ]

This way, we have added the django_filters application to our Django project named restful01.

The default query parameter names are search for the search feature and ordering for the ordering feature. We can specify other names by setting the desired strings in the SEARCH_PARAM and the ORDERING_PARAM settings. In this case, we will work with the default values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset