ash
ash

Reputation: 75

Custom filter with Django Filters

I am trying to write my own custom filter class as follows using django_filters:

from django_filters import rest_framework as filters


class FooFilter(filters.FilterSet):
    class Meta:
        model = Model 
        fields = ['custom_field',]


class Foo():
    filter_backends = (filters.DjangoFilterBackend,)
    filterset_class = FooFilter

In models, as I do not have the field custom_field, it will give the error: TypeError: 'Meta.fields' must not contain non-model field names: custom_field

Question: Is it possible to define my own custom query that is a non-model field name using Django Filterset?

Upvotes: 2

Views: 11501

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can define an arbitrary function that will filter the queryset further. For example:

class MyFilterSet(FilterSet):
    custom_field = CharFilter(method='filter_not_empty')

    def filter_custom_field(queryset, name, value):
        return queryset.filter(… some filtering …)

    class Meta:
        model = Model
        fields = ['custom_field']

Here we thus define a CharFilter for custom_field that thus will parse a string. With `method='filter_not_empty', we refer to the method that will be called.

This method is called with a queryset that needs to be filtered, name is the name of the filter field (here it is custom_field, but you can, if you want, use the same method for multiple filter set fields), and the value.

The method should return a QuerySet that is filtered down with … some filtering …

Upvotes: 6

Related Questions