How use MethodFilter from django-filter app?

Question:

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).

Asked By: merenptah

||

Answers:

I’m not sure I understand fully what you’re asking, but to filter your products you can use Q

https://docs.djangoproject.com/en/1.7/topics/db/queries/#complex-lookups-with-q

from django.db.models import Q
queryset = Products.objects.filter(Q(created_at__gte=from)&Q(created_at__ite=to)
Answered By: user2021091

I searched in GitHub and I found this. It works.

class DateRangeField(django_filters.fields.RangeField):
    # Django-Filter DateRangeFilter that really accepts a range of dates ;)
    def __init__(self, *args, **kwargs):
        fields = (
            forms.DateField(),
            forms.DateField(),
        )
        forms.MultiValueField.__init__(self, fields, *args, **kwargs)


class DateRangeFilter(django_filters.RangeFilter):
    field_class = DateRangeField
Answered By: merenptah

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
        )
Answered By: Carlton Gibson

for newer versions

created_at = django_filters.DateFromToRangeFilter(widget=django_filters.widgets.RangeWidget(attrs={'type': 'date'}))
Answered By: Carlos Leite
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.