![](/img/trans.png)
[英]“Invalid Filter” error for my custom Django template filters but not any other filters
[英]Custom filter with Django Filters
我正在尝试使用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
在模型中,由于我没有字段custom_field
,它会给出错误: TypeError: 'Meta.fields' must not contain non-model field names: custom_field
问题:是否可以使用 Django Filterset 定义我自己的非模型字段名称的自定义查询?
您可以定义一个任意函数来进一步过滤查询集。 例如:
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']
因此,我们在这里为custom_field
定义了一个CharFilter
,它将解析一个字符串。 使用`method='filter_not_empty',我们指的是将被调用的方法。
这种方法被称为一个queryset
将要过滤的需求, name
是过滤器字段的名称(这里是custom_field
,但你可以,如果你愿意,使用多种过滤器设置字段同样的方法),和价值。
该方法应该返回一个QuerySet
,该QuerySet
被过滤了… some filtering …
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.