Django-filter: The django_filters.BooleanFilter with method and a boolean filter inherited from a model don't work on a same way.

Created on 24 Apr 2017  ·  3Comments  ·  Source: carltongibson/django-filter

I've encountered an issue that the boolean filter created by django_filters.BooleanFilter expects different query params with the boolean filter inherited from the model.
Boolean filter inherited from the model expects the param to be true or false, a filter created by BooleanFilter expects the params to be either:
1 - translated to "not set"
2 - translated to "True"
3 - translated to "False"
This behavior make it unclear how to process rest api custom filter's from the javascript side.

Example code:

models.py:
class TestModel(models.Model): first = models.BooleanField() last = models.BooleanField()
api.py

`import django_filters
from rest_framework import viewsets, serializers
from .models import TestModel

class TestFilter(django_filters.rest_framework.FilterSet):
first_and_last = django_filters.BooleanFilter(method='first_and_last_filter')
def first_and_last_filter(self, queryset, name, value):
if value==True:
return queryset.filter(first=True, last=True);
return queryset;
class Meta:
model = TestModel
fields = ['first', 'last', 'first_and_last']

class TestSerializer(serializers.ModelSerializer):
class Meta:
model = TestModel
fields = ['first', 'last']

class TestViewSet(viewsets.ModelViewSet):
model = TestModel
queryset = TestModel.objects.all()
serializer_class = TestSerializer
filter_backends = (django_filters.rest_framework.DjangoFilterBackend,)
filter_fields = ('first', 'last', 'first_and_last', )
filter_class = TestFilter`

The test viewset filter here expects the query param to be "true" or "false" for the "first" and "last" fields, but expects it to be 1,2 or 3 for the "first_and_last" filter field.
For example filtering query cold be like this:
/api/test/?first=true&first_and_last=2

This is a simplified example in the real project I've encountered it the custom filter contains more complicated logic.
I've set up the repo with all the code needed to reproduce the issue.
https://github.com/inakrin/boolfilter

Most helpful comment

Hi @inakrin. You should import filters from the rest_framework sub-package.

https://github.com/carltongibson/django-filter/blob/develop/django_filters/rest_framework/filters.py

All 3 comments

Hi @inakrin. You should import filters from the rest_framework sub-package.

https://github.com/carltongibson/django-filter/blob/develop/django_filters/rest_framework/filters.py

So it probably should be mentioned in DRF documentation because they suggest to import from filters:
http://www.django-rest-framework.org/api-guide/filtering/#specifying-a-filterset
And it works of course in all the cases except BooleanFilter.

Was this page helpful?
0 / 5 - 0 ratings