merenptah merenptah - 1 month ago 22
Python Question

How use MethodFilter from django-filter app?

I don't know how to use MethodFilter in django-filter app and I can't find it in the documentation (http://django-filter.readthedocs.org/en/latest/index.html). I need create filter with from and to input for date field. Do you have any idea how I can do this with MethodFilter or another way?

I have some class:

class Product(django_filters.FilterSet):

class Meta:
model = Product
fields = ['name', 'category', 'created_at]


I have field created_at and I want to filter products by created_at (from and to).

Answer

To answer the How to use MethodFilter part of the question, define a method on your FilterSet and assign that as the filter's action.

For example to filter by a username you would do something such as:

class F(FilterSet):
    username = MethodFilter(action='filter_username')

    class Meta:
        model = User
        fields = ['username']

    def filter_username(self, queryset, value):
        return queryset.filter(
            username=value
        )