[Fixed]-Django Rest Framework filter class method with two parameters

1👍

In order to achieve this, I found that Django Rest Framework has a class that extends from django_filters. This class is called BaseFilterBackend and can be used to extend the default backend for filtering any request. So what I did was adding a class extended from BaseFilterBackend like this:

from rest_framework import filters

class FatherFilterBackend(filters.BaseFilterBackend):
   def filter_queryset(self, request, queryset, view):
      daughter_id = request.query_params.get("daughter_id", None)
      daughter_name = request.query_params.get("daughter_name", None)

      if daughter_id and daughter_name:
         kwargs = {
            daughter_name: daughter_id
         }
         queryset = queryset.filter(**kwargs)

      return queryset

This filter will apply before others, so even if you are using a FilterSet class, you will not lose the filters from your BaseFilterBackend. The problem with this solution is that relies in rest_framework.filters package, a filter that its not related to django_filters.

This might not be the best way to achieve this, so if you have better ideas please add them to help others with a similar problem.

Leave a comment