如何使用django-filter app中的MethodFilter?

mer*_*tah 2 python django django-filters

我不知道如何在django-filter app中使用MethodFilter,我在文档中找不到它(http://django-filter.readthedocs.org/en/latest/index.html).我需要创建过滤器,使用from和to输入日期字段.您是否知道如何使用MethodFilter或其他方式执行此操作?

我有一些课:

class Product(django_filters.FilterSet):

    class Meta:
        model = Product
        fields = ['name', 'category', 'created_at]
Run Code Online (Sandbox Code Playgroud)

我有字段created_at,我想通过created_at(from和to)过滤产品.

Car*_*son 10

要回答如何使用MethodFilter问题的一部分,请在您的方法上定义一个方法FilterSet并将其指定为过滤器action.

例如,要按用户名进行过滤,您可以执行以下操作:

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
        )
Run Code Online (Sandbox Code Playgroud)