django-filter¶
Django-filter是一个通用的,可重用的应用程序,可减轻编写视图代码中一些平凡的工作的负担。 具体来说,它允许用户根据模型的字段过滤查询集,并显示表单以允许他们执行此操作。
Installation¶
可以使用pip
之类的工具从PyPI安装Django-filter:
$ pip install django-filter
Then add 'django_filters'
to your INSTALLED_APPS
.
INSTALLED_APPS = [
...
'django_filters',
]
Getting Started¶
Django-filter提供了一种简单的方法来根据用户提供的参数过滤查询集。 假设我们有一个Product
模型,我们想让我们的用户过滤他们在列表页面上看到的产品。
Note
如果您将django-filter与Django Rest Framework结合使用,建议您阅读本指南之后的集成文档。
The model¶
Let’s start with our model:
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=255)
price = models.DecimalField()
description = models.TextField()
release_date = models.DateField()
manufacturer = models.ForeignKey(Manufacturer)
The filter¶
我们有许多字段,我们想让我们的用户根据名称,price或release_date进行过滤。 We create a FilterSet
for this:
import django_filters
class ProductFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='iexact')
class Meta:
model = Product
fields = ['price', 'release_date']
如您所见,它使用了与Django ModelForm
非常相似的API。 就像使用ModelForm
一样,我们也可以覆盖过滤器,或使用声明性语法添加新的过滤器。
Declaring filters¶
The declarative syntax provides you with the most flexibility when creating
filters, however it is fairly verbose. We’ll use the below example to outline
the core filter arguments on a FilterSet
:
class ProductFilter(django_filters.FilterSet):
price = django_filters.NumberFilter()
price__gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt')
price__lt = django_filters.NumberFilter(field_name='price', lookup_expr='lt')
release_year = django_filters.NumberFilter(field_name='release_date', lookup_expr='year')
release_year__gt = django_filters.NumberFilter(field_name='release_date', lookup_expr='year__gt')
release_year__lt = django_filters.NumberFilter(field_name='release_date', lookup_expr='year__lt')
manufacturer__name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = Product
There are two main arguments for filters:
field_name
: The name of the model field to filter on. You can traverse “relationship paths” using Django’s__
syntax to filter fields on a related model. ex,manufacturer__name
.lookup_expr
: The field lookup to use when filtering. Django’s__
syntax can again be used in order to support lookup transforms. ex,year__gte
.
Together, the field field_name
and lookup_expr
represent a complete Django
lookup expression. A detailed explanation of lookup expressions is provided in
Django’s lookup reference. django-filter supports expressions containing
both transforms and a final lookup.
Generating filters with Meta.fields¶
The FilterSet Meta class provides a fields
attribute that can be used for
easily specifying multiple filters without significant code duplication. The
base syntax supports a list of multiple field names:
import django_filters
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = ['price', 'release_date']
The above generates ‘exact’ lookups for both the ‘price’ and ‘release_date’ fields.
Additionally, a dictionary can be used to specify multiple lookup expressions for each field:
import django_filters
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = {
'price': ['lt', 'gt'],
'release_date': ['exact', 'year__gt'],
}
The above would generate ‘price__lt’, ‘price__gt’, ‘release_date’, and ‘release_date__year__gt’ filters.
Note
The filter lookup type ‘exact’ is an implicit default and therefore never added to a filter name. In the above example, the release date’s exact filter is ‘release_date’, not ‘release_date__exact’.
Items in the fields
sequence in the Meta
class may include
“relationship paths” using Django’s __
syntax to filter on fields on a
related model:
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = ['manufacturer__country']
Overriding default filters¶
Like django.contrib.admin.ModelAdmin
, it is possible to override
default filters for all the models fields of the same kind using
filter_overrides
on the Meta
class:
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = {
'name': ['exact'],
'release_date': ['isnull'],
}
filter_overrides = {
models.CharField: {
'filter_class': django_filters.CharFilter,
'extra': lambda f: {
'lookup_expr': 'icontains',
},
},
models.BooleanField: {
'filter_class': django_filters.BooleanFilter,
'extra': lambda f: {
'widget': forms.CheckboxInput,
},
},
}
Request-based filtering¶
The FilterSet
may be initialized with an optional request
argument. If
a request object is passed, then you may access the request during filtering.
This allows you to filter by properties on the request, such as the currently
logged-in user or the Accepts-Languages
header.
Note
It is not guaranteed that a request will be provied to the FilterSet instance. Any code depending on a request should handle the None case.
Filtering the primary .qs
¶
To filter the primary queryset by the request
object, simply override the
FilterSet.qs
property. For example, you could filter blog articles to only
those that are published and those that are owned by the logged-in user
(presumably the author’s draft articles).
class ArticleFilter(django_filters.FilterSet):
class Meta:
model = Article
fields = [...]
@property
def qs(self):
parent = super(ArticleFilter, self).qs
author = getattr(self.request, 'user', None)
return parent.filter(is_published=True) \
| parent.filter(author=author)
Customize filtering with Filter.method
¶
You can control the behavior of a filter by specifying a method
to perform
filtering. View more information in the method reference.
Note that you may access the filterset’s properties, such as the request
.
class F(django_filters.FilterSet):
username = CharFilter(method='my_custom_filter')
class Meta:
model = User
fields = ['username']
def my_custom_filter(self, queryset, name, value):
return queryset.filter(**{
name: value,
})
The view¶
Now we need to write a view:
def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
return render(request, 'my_app/template.html', {'filter': f})
If a queryset argument isn’t provided then all the items in the default manager of the model will be used.
If you want to access the filtered objects in your views, for example if you want to paginate them, you can do that. They are in f.qs
The template¶
And lastly we need a template:
{% extends "base.html" %}
{% block content %}
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit" />
</form>
{% for obj in filter.qs %}
{{ obj.name }} - ${{ obj.price }}<br />
{% endfor %}
{% endblock %}
And that’s all there is to it! The form
attribute contains a normal
Django form, and when we iterate over the FilterSet.qs
we get the objects in
the resulting queryset.
Generic view & configuration¶
In addition to the above usage there is also a class-based generic view
included in django-filter, which lives at django_filters.views.FilterView
.
You must provide either a model
or filterset_class
argument, similar to
ListView
in Django itself:
# urls.py
from django.conf.urls import url
from django_filters.views import FilterView
from myapp.models import Product
urlpatterns = [
url(r'^list/$', FilterView.as_view(model=Product)),
]
If you provide a model
optionally you can set filterset_fields
to specify a list or a tuple of
the fields that you want to include for the automatic construction of the filterset class.
You must provide a template at <app>/<model>_filter.html
which gets the
context parameter filter
. Additionally, the context will contain
object_list
which holds the filtered queryset.
A legacy functional generic view is still included in django-filter, although
its use is deprecated. It can be found at
django_filters.views.object_filter
. You must provide the same arguments
to it as the class based view:
# urls.py
from django.conf.urls import url
from django_filters.views import object_filter
from myapp.models import Product
urlpatterns = [
url(r'^list/$', object_filter, {'model': Product}),
]
The needed template and its context variables will also be the same as the class-based view above.
与DRF集成¶
通过DRF特定的FilterSet
和过滤器后端提供与Django Rest Framework的集成。 这些可以在rest_framework
子包中找到。
Quickstart¶
使用新的FilterSet
只需要更改导入路径。 而不是从django_filters
导入,而是从rest_framework
子包导入。
from django_filters import rest_framework as filters
class ProductFilter(filters.FilterSet):
...
您的视图类还需要将DjangoFilterBackend
添加到filter_backends
。
from django_filters import rest_framework as filters
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ('category', 'in_stock')
如果要在默认情况下使用django-filter后端,请将其添加到DEFAULT_FILTER_BACKENDS
设置。
# settings.py
INSTALLED_APPS = [
...
'rest_framework',
'django_filters',
]
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
...
),
}
使用filterset_class
添加FilterSet ¶
要使用FilterSet
启用过滤,请将其添加到视图类的filterset_class
参数。
from rest_framework import generics
from django_filters import rest_framework as filters
from myapp import Product
class ProductFilter(filters.FilterSet):
min_price = filters.NumberFilter(field_name="price", lookup_expr='gte')
max_price = filters.NumberFilter(field_name="price", lookup_expr='lte')
class Meta:
model = Product
fields = ['category', 'in_stock', 'min_price', 'max_price']
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_class = ProductFilter
使用filterset_fields
快捷键¶
您可以通过将filterset_fields
添加到视图类来绕过创建FilterSet
。 这相当于只用Meta.fields创建一个FilterSet。
from rest_framework import generics
from django_filters import rest_framework as filters
from myapp import Product
class ProductList(generics.ListAPIView):
queryset = Product.objects.all()
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ('category', 'in_stock')
# Equivalent FilterSet:
class ProductFilter(filters.FilterSet):
class Meta:
model = Product
fields = ('category', 'in_stock')
请注意,不支持同时使用filterset_fields
和filterset_class
。
覆盖FilterSet创建¶
可以通过覆盖后端类的以下方法来自定义FilterSet
创建:
.get_filterset(self, request, queryset, view)
.get_filterset_class(self, view, queryset=None)
.get_filterset_kwargs(self, request, queryset, view)
您可以根据具体情况为每个视图覆盖这些方法,创建唯一的后端,或者可以使用这些方法将自己的钩子写入视图类。
class MyFilterBackend(filters.DjangoFilterBackend):
def get_filterset_kwargs(self, request, queryset, view):
kwargs = super().get_filterset_kwargs(request, queryset, view)
# merge filterset kwargs provided by view class
if hasattr(view, 'get_filterset_kwargs'):
kwargs.update(view.get_filterset_kwargs())
return kwargs
class BooksFilter(filters.FilterSet):
def __init__(self, *args, author=None, **kwargs):
super().__init__(*args, **kwargs)
# do something w/ author
class BookViewSet(viewsets.ModelViewSet):
filter_backends = [MyFilterBackend]
filterset_class = BookFilter
def get_filterset_kwargs(self):
return {
'author': self.get_author(),
}
Schema Generation with Core API and Open API¶
后端类通过实现get_schema_fields()
和get_schema_operation_parameters()
来集成DRF的模式生成。 安装Core API时会自动启用get_schema_fields()
。 get_schema_operation_parameters()
始终为Open API启用(DRF 3.9以来的新功能)。 模式生成通常无缝地运行,但实现确实需要调用视图的get_queryset()
方法。 有一点需要注意,在模式生成期间人工构造视图,因此args
和kwargs
属性将为空。 如果依赖于从URL解析的参数,则需要在get_queryset()
中处理它们的缺失。
例如,您的get queryset方法可能如下所示:
class IssueViewSet(views.ModelViewSet):
queryset = models.Issue.objects.all()
def get_project(self):
return models.Project.objects.get(pk=self.kwargs['project_id'])
def get_queryset(self):
project = self.get_project()
return self.queryset \
.filter(project=project) \
.filter(author=self.request.user)
这可以像这样重写:
class IssueViewSet(views.ModelViewSet):
queryset = models.Issue.objects.all()
def get_project(self):
try:
return models.Project.objects.get(pk=self.kwargs['project_id'])
except models.Project.DoesNotExist:
return None
def get_queryset(self):
project = self.get_project()
if project is None:
return self.queryset.none()
return self.queryset \
.filter(project=project) \
.filter(author=self.request.user)
Or more simply as:
class IssueViewSet(views.ModelViewSet):
queryset = models.Issue.objects.all()
def get_queryset(self):
# project_id may be None
return self.queryset \
.filter(project_id=self.kwargs.get('project_id')) \
.filter(author=self.request.user)
Crispy Forms¶
如果您正在使用DRF的可浏览API或管理API,您可能还需要安装django-crispy-forms
,这将通过允许它们呈现Bootstrap 3 HTML来增强HTML视图中过滤器表单的呈现。 请注意,虽然欢迎提出针对错误修复的拉取请求,但不会主动支持此操作。
pip install django-crispy-forms
安装了crispy表单并添加到Django的INSTALLED_APPS
,可浏览的API将为DjangoFilterBackend
提供过滤控件,如下所示:
Additional FilterSet
Features¶
以下功能特定于其余框架FilterSet:
BooleanFilter
使用API友好的BooleanWidget
,它接受小写true
/false
。- 过滤器生成使用
IsoDateTimeFilter
作为日期时间模型字段。 - 引发的
ValidationError
被重新标记为DRF等效项。
提示和解决方案¶
声明过滤器的常见问题¶
以下是声明过滤器时出现的一些常见问题。 建议您阅读本文,因为它可以更全面地了解过滤器的工作原理。
过滤field_name
和lookup_expr
未配置¶
虽然field_name
和lookup_expr
是可选的,但建议您指定它们。 默认情况下,如果未指定field_name
,将使用filterset类上的过滤器名称。 此外,lookup_expr
默认为exact
。 以下是错误配置的价格过滤器示例:
class ProductFilter(django_filters.FilterSet):
price__gt = django_filters.NumberFilter()
过滤器实例的字段名称为price__gt
,exact_精确
查找类型。 在引擎盖下,这将被错误地解决为:
Produce.objects.filter(price__gt__exact=value)
以上内容很可能会产生FieldError
。 正确的配置是:
class ProductFilter(django_filters.FilterSet):
price__gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt')
文本搜索过滤器缺少lookup_expr
¶
忘记为CharField
和TextField
设置查找表达式是很常见的,并且想知道为什么搜索“foo”不会返回“foobar”的结果。 这是因为默认查找类型是exact
,但您可能希望执行icontains
查找。
过滤和查找表达式不匹配(in,range,isnull)¶
将过滤器直接匹配到其模型字段的类型并不总是合适的,因为一些查找期望不同类型的值。 这是in
,range
和isnull
查找中常见的问题。 Let’s look
at the following product model:
class Product(models.Model):
category = models.ForeignKey(Category, null=True)
鉴于category
是可选的,因此想要搜索未分类的产品是合理的。 以下是错误配置的isnull
过滤器:
class ProductFilter(django_filters.FilterSet):
uncategorized = django_filters.NumberFilter(field_name='category', lookup_expr='isnull')
So what’s the issue? 虽然category
的基础列类型是整数,但isnull
查找期望一个布尔值。 但是NumberFilter
只能验证数字。 过滤器不是'表达式识别',并且不会根据lookup_expr
更改行为。 您应该使用与查找表达式的数据类型匹配的过滤器,而不是模型字段下面的数据类型的。 以下内容将正确地允许您针对一组类别搜索未分类的产品和产品:
class NumberInFilter(django_filters.BaseInFilter, django_filters.NumberFilter):
pass
class ProductFilter(django_filters.FilterSet):
categories = NumberInFilter(field_name='category', lookup_expr='in')
uncategorized = django_filters.BooleanFilter(field_name='category', lookup_expr='isnull')
More info on constructing in
and range
csv filters.
按空值过滤¶
在许多情况下,您可能需要按空值或空值进行过滤。 以下是这些问题的一些常见解决方案:
按空值过滤¶
如上面的“过滤器和查找表达式不匹配”部分所述,常见的问题是如何正确过滤字段上的空值。
Solution 1: Using a BooleanFilter
with isnull
¶
使用BooleanFilter
和isnull
查找是FilterSet自动生成过滤器所使用的内置解决方案。 要手动执行此操作,只需添加:
class ProductFilter(django_filters.FilterSet):
uncategorized = django_filters.BooleanFilter(field_name='category', lookup_expr='isnull')
Note
请记住,过滤器类正在验证输入值。 模式字段的基础类型与此无关。
您也可以使用exclude
参数反转逻辑。
class ProductFilter(django_filters.FilterSet):
has_category = django_filters.BooleanFilter(field_name='category', lookup_expr='isnull', exclude=True)
Solution 2: Using ChoiceFilter
’s null choice¶
如果您正在使用ChoiceFilter,则还可以通过启用null_label
参数来过滤空值。 ChoiceFilter
参考docs中的更多细节。
class ProductFilter(django_filters.FilterSet):
category = django_filters.ModelChoiceFilter(
field_name='category', lookup_expr='isnull',
null_label='Uncategorized',
queryset=Category.objects.all(),
)
解决方案3:组合字段w / MultiValueField
¶
另一种方法是使用Django的MultiValueField
手动添加BooleanField
来处理空值。 Proof of concept:
https://github.com/carltongibson/django-filter/issues/446
Filtering by an empty string¶
目前无法通过空字符串进行过滤,因为空值被解释为跳过的过滤器。
Solution 1: Magic values¶
您可以覆盖过滤器类的filter()
方法,以专门检查魔术值。 这类似于ChoiceFilter
的空值处理。
class MyCharFilter(filters.CharFilter):
empty_value = 'EMPTY'
def filter(self, qs, value):
if value != self.empty_value:
return super(MyCharFilter, self).filter(qs, value)
qs = self.get_method(qs)(**{'%s__%s' % (self.name, self.lookup_expr): ""})
return qs.distinct() if self.distinct else qs
Solution 2: Empty string filter¶
It would also be possible to create an empty value filter that exhibits the same
behavior as an isnull
filter.
from django.core.validators import EMPTY_VALUES
class EmptyStringFilter(filters.BooleanFilter):
def filter(self, qs, value):
if value in EMPTY_VALUES:
return qs
exclude = self.exclude ^ (value is False)
method = qs.exclude if exclude else qs.filter
return method(**{self.name: ""})
class MyFilterSet(filters.FilterSet):
myfield__isempty = EmptyStringFilter(field_name='myfield')
class Meta:
model = MyModel
Using initial
values as defaults¶
在1.0版本的django-filter中,当没有提交任何值时,过滤器字段的initial
值被用作默认值。 此行为未得到官方支持,并已被删除。
Warning
It is recommended that you do NOT implement the below as it adversely affects usability. Django forms don’t provide this behavior for a reason.
- Using initial values as defaults is inconsistent with the behavior of Django forms.
- Default values prevent users from filtering by empty values.
- Default values prevent users from skipping that filter.
如果需要默认值,则以下内容应模仿1.0之前的行为:
class BaseFilterSet(FilterSet):
def __init__(self, data=None, *args, **kwargs):
# if filterset is bound, use initial values as defaults
if data is not None:
# get a mutable copy of the QueryDict
data = data.copy()
for name, f in self.base_filters.items():
initial = f.extra.get('initial')
# filter param is either missing or empty, use initial as default
if not data.get(name) and initial:
data[name] = initial
super(BaseFilterSet, self).__init__(data, *args, **kwargs)
Migration Guide¶
启用警告¶
要查看弃用,您可能需要在python中启用警告。 这可以通过-W
标志或PYTHONWARNINGS
环境变量来实现。 For example, you could run your test suite like so:
$ python -W once manage.py test
上述内容会在首次出现时打印所有警告。 这有助于了解代码中存在哪些违规(或偶尔在第三方代码中)。 但是,它只打印堆栈跟踪的最后一行。 您可以使用以下内容来引发完整的异常:
$ python -W error manage.py test
Migrating to 2.0¶
此版本包含一些打破向前兼容性的更改。 这包括已删除的功能,重命名的属性和参数以及一些重新设计的功能。 由于这些更改的性质,发布完全向前兼容的迁移版本是不可行的。 请查看以下更改列表并相应更新您的代码。
Filter.lookup_expr
list form removed (#851)¶
Filter.lookup_expr
参数不再接受无
或表达式列表。 请改用LookupChoiceFilter。
FilterSet filter_for_reverse_field
removed (#915)¶
The filter_for_field
method now generates filters for reverse relationships,
removing the need for filter_for_reverse_field
. As a result, reverse
relationships now also obey Meta.filter_overrides
.
View attributes renamed (#867)¶
Several view-related attributes have been renamed to improve consistency with other parts of the library. The following classes are affected:
- DRF
ViewSet.filter_class
=>filterset_class
- DRF
ViewSet.filter_fields
=>filterset_fields
DjangoFilterBackend.default_filter_set
=>filterset_base
DjangoFilterBackend.get_filter_class()
=>get_filterset_class()
FilterMixin.filter_fields
=>filterset_fields
FilterSet Meta.together
option removed (#791)¶
The Meta.together
has been deprecated in favor of userland implementations
that override the clean
method of the Meta.form
class. An example will
be provided in a “recipes” section in future docs.
FilterSet “strictness” handling moved to view (#788)¶
Strictness handling has been removed from the FilterSet
and added to the
view layer. As a result, the FILTERS_STRICTNESS
setting, Meta.strict
option, and strict
argument for the FilterSet
initializer have all
been removed.
To alter strictness behavior, the appropriate view code should be overridden. More details will be provided in future docs.
Filter.name
renamed to Filter.field_name
(#792)¶
The filter name
has been renamed to field_name
as a way to disambiguate
the filter’s attribute name on its FilterSet class from the field_name
used
for filtering purposes.
Filter.widget
and Filter.required
removed (#734)¶
The filter class no longer directly stores arguments passed to its form field.
All arguments are located in the filter’s .extra
dict.
MultiWidget
replaced by SuffixedMultiWidget
(#770)¶
RangeWidget
, DateRangeWidget
, and LookupTypeWidget
now inherit from
SuffixedMultiWidget
, changing the suffixes of their query param names. For
example, RangeWidget
now has _min
and _max
suffixes instead of
_0
and _1
.
Filters like RangeFilter, DateRangeFilter, DateTimeFromToRangeFilter...
(#770)¶
- As they depend on
MultiWidget
, they need to be adjusted. In 1.0 release - parameters were provided using
_0
and_1
as suffix``. For example, a parametercreation_date
using``DateRangeFilter`` will expectcreation_date_after
andcreation_date_before
instead ofcreation_date_0
andcreation_date_1
.
Migrating to 1.0¶
The 1.0 release of django-filter introduces several API changes and refinements that break forwards compatibility. Below is a list of deprecations and instructions on how to migrate to the 1.0 release. A forwards-compatible 0.15 release has also been created to help with migration. It is compatible with both the existing and new APIs and will raise warnings for deprecated behavior.
MethodFilter and Filter.action replaced by Filter.method (#382)¶
The functionality of MethodFilter
and Filter.action
has been merged
together and replaced by the Filter.method
parameter. The method
parameter takes either a callable or the name of a FilterSet
method. The
signature now takes an additional name
argument that is the name of the
model field to be filtered on.
Since method
is now a parameter of all filters, inputs are validated and
cleaned by its field_class
. The function will receive the cleaned value
instead of the raw value.
# 0.x
class UserFilter(FilterSet):
last_login = filters.MethodFilter()
def filter_last_login(self, qs, value):
# try to convert value to datetime, which may fail.
if value and looks_like_a_date(value):
value = datetime(value)
return qs.filter(last_login=value})
# 1.0
class UserFilter(FilterSet):
last_login = filters.CharFilter(method='filter_last_login')
def filter_last_login(self, qs, name, value):
return qs.filter(**{name: value})
QuerySet methods are no longer proxied (#440)¶
The __iter__()
, __len__()
, __getitem__()
, count()
methods are
no longer proxied from the queryset. To fix this, call the methods on the
.qs
property itself.
f = UserFilter(request.GET, queryset=User.objects.all())
# 0.x
for obj in f:
...
# 1.0
for obj in f.qs:
...
Filters no longer autogenerated when Meta.fields is not specified (#450)¶
FilterSets had an undocumented behavior of autogenerating filters for all
model fields when either Meta.fields
was not specified or when set to
None
. This can lead to potentially unsafe data or schema exposure and
has been deprecated in favor of explicitly setting Meta.fields
to the
'__all__'
special value. You may also blacklist fields by setting
the Meta.exclude
attribute.
class UserFilter(FilterSet):
class Meta:
model = User
fields = '__all__'
# or
class UserFilter(FilterSet):
class Meta:
model = User
exclude = ['password']
Move FilterSet options to Meta class (#430)¶
Several FilterSet
options have been moved to the Meta
class to prevent
potential conflicts with declared filter names. This includes:
filter_overrides
strict
order_by_field
# 0.x
class UserFilter(FilterSet):
filter_overrides = {}
strict = STRICTNESS.RAISE_VALIDATION_ERROR
order_by_field = 'order'
...
# 1.0
class UserFilter(FilterSet):
...
class Meta:
filter_overrides = {}
strict = STRICTNESS.RAISE_VALIDATION_ERROR
order_by_field = 'order'
FilterSet ordering replaced by OrderingFilter (#472)¶
The FilterSet ordering options and methods have been deprecated and replaced by OrderingFilter. Deprecated options include:
Meta.order_by
Meta.order_by_field
These options retain backwards compatibility with the following caveats:
order_by
asserts thatMeta.fields
is not using the dict syntax. This previously was undefined behavior, however the migration code is unable to support it.Prior, if no ordering was specified in the request, the FilterSet implicitly filtered by the first param in the
order_by
option. This behavior cannot be easily emulated but can be fixed by ensuring that the passed in queryset explicitly calls.order_by()
.filterset = MyFilterSet(queryset=MyModel.objects.order_by('field'))
The following methods are deprecated and will raise an assertion if present on the FilterSet:
.get_order_by()
.get_ordering_field()
To fix this, simply remove the methods from your class. You can subclass
OrderingFilter
to migrate any custom logic.
Deprecated FILTERS_HELP_TEXT_FILTER
and FILTERS_HELP_TEXT_EXCLUDE
(#437)¶
Generated filter labels in 1.0 will be more descriptive, including humanized text about the lookup being performed and if the filter is an exclusion filter.
These settings will no longer have an effect and will be removed in the 1.0 release.
FilterSet Options¶
本文档提供了有关使用其他FilterSet功能的指南。
Meta options¶
使用模型生成自动过滤器
¶
FilterSet
能够自动为给定的model
字段生成过滤器。 与Django的ModelForm
类似,过滤器是基于底层模型字段的类型创建的。 此选项必须与fields
或exclude
选项结合使用,这与Django的ModelForm
类的要求相同,详细此处。
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = ['username', 'last_login']
声明可过滤的fields
¶
fields
选项与model
组合以自动生成过滤器。 请注意,生成的过滤器不会覆盖FilterSet
上声明的过滤器。 fields
选项接受两种语法:
- 字段名称列表
- 映射到查找列表的字段名称字典
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = ['username', 'last_login']
# or
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
fields = {
'username': ['exact', 'contains'],
'last_login': ['exact', 'year__gt'],
}
列表语法将为fields
中包含的每个字段创建exact
查找过滤器。 字典语法将为为其对应的模型字段声明的每个查找表达式创建一个过滤器。 这些表达式可能包括转换和查找,如查找引用中所述。
Disable filter fields with exclude
¶
exclude
选项接受要从自动过滤器生成中排除的字段名称黑名单。 请注意,此选项不会禁用直接在FilterSet
上声明的过滤器。
class UserFilter(django_filters.FilterSet):
class Meta:
model = User
exclude = ['password']
Custom Forms using form
¶
The inner Meta
class also takes an optional form
argument. This is a
form class from which FilterSet.form
will subclass. This works similar to
the form
option on a ModelAdmin.
Customise filter generation with filter_overrides
¶
The inner Meta
class also takes an optional filter_overrides
argument.
This is a map of model fields to filter classes with options:
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = ['name', 'release_date']
filter_overrides = {
models.CharField: {
'filter_class': django_filters.CharFilter,
'extra': lambda f: {
'lookup_expr': 'icontains',
},
},
models.BooleanField: {
'filter_class': django_filters.BooleanFilter,
'extra': lambda f: {
'widget': forms.CheckboxInput,
},
},
}
Overriding FilterSet
methods¶
When overriding classmethods, calling super(MyFilterSet, cls)
may result
in a NameError
exception. This is due to the FilterSetMetaclass
calling
these classmethods before the FilterSet
class has been fully created.
There are two recommmended workarounds:
If using python 3.6 or newer, use the argumentless
super()
syntax.For older versions of python, use an intermediate class. Ex:
class Intermediate(django_filters.FilterSet): @classmethod def method(cls, arg): super(Intermediate, cls).method(arg) ... class ProductFilter(Intermediate): class Meta: model = Product fields = ['...']
filter_for_lookup()
¶
在版本0.13.0之前,过滤器生成没有考虑使用的lookup_expr
。 这通常会导致为'isnull','in'和'range'查找(以及转换后的查找)生成格式错误的过滤器。 当前实现提供以下行为:
- ‘isnull’ lookups return a
BooleanFilter
- 'in'查找返回从基于CSV的
BaseInFilter
派生的过滤器。 - ‘range’ lookups return a filter derived from the CSV-based
BaseRangeFilter
.
如果要覆盖用于实例化模型字段的过滤器的filter_class
和params
,则可以覆盖filter_for_lookup()
。 Ex:
class ProductFilter(django_filters.FilterSet):
class Meta:
model = Product
fields = {
'release_date': ['exact', 'range'],
}
@classmethod
def filter_for_lookup(cls, f, lookup_type):
# override date range lookups
if isinstance(f, models.DateField) and lookup_type == 'range':
return django_filters.DateRangeFilter, {}
# use default behavior otherwise
return super().filter_for_lookup(f, lookup_type)
Filter Reference¶
这是一个参考文档,其中包含过滤器及其参数的列表。
Core Arguments¶
以下是适用于所有过滤器的核心参数。 请注意,它们被连接起来构造完整的查找表达式,它是ORM .filter()
调用的左侧。
field_name
¶
The name of the model field that is filtered against. If this argument is not
provided, it defaults the filter’s attribute name on the FilterSet
class.
Field names can traverse relationships by joining the related parts with the ORM
lookup separator (__
). e.g., a product’s manufacturer__name
.
lookup_expr
¶
The field lookup that should be performed in the filter call. Defaults to
exact
. The lookup_expr
can contain transforms if the expression parts
are joined by the ORM lookup separator (__
). e.g., filter a datetime by its
year part year__gt
.
Keyword-only Arguments:¶
The following are optional arguments that can be used to modify the behavior of all filters.
label
¶
The label as it will appear in the HTML, analogous to a form field’s label
argument. If a label is not provided, a verbose label will be generated based
on the field field_name
and the parts of the lookup_expr
(see: FILTERS_VERBOSE_LOOKUPS).
method
¶
An optional argument that tells the filter how to handle the queryset. It can
accept either a callable or the name of a method on the FilterSet
. The
callable receives a QuerySet
, the name of the model field to filter on, and
the value to filter with. It should return a filtered Queryset
.
Note that the value is validated by the Filter.field
, so raw value
transformation and empty value checking should be unnecessary.
class F(FilterSet):
"""Filter for Books by if books are published or not"""
published = BooleanFilter(field_name='published_on', method='filter_published')
def filter_published(self, queryset, name, value):
# construct the full lookup expression.
lookup = '__'.join([name, 'isnull'])
return queryset.filter(**{lookup: False})
# alternatively, it may not be necessary to construct the lookup.
return queryset.filter(published_on__isnull=False)
class Meta:
model = Book
fields = ['published']
# Callables may also be defined out of the class scope.
def filter_not_empty(queryset, name, value):
lookup = '__'.join([name, 'isnull'])
return queryset.filter(**{lookup: False})
class F(FilterSet):
"""Filter for Books by if books are published or not"""
published = BooleanFilter(field_name='published_on', method=filter_not_empty)
class Meta:
model = Book
fields = ['published']
distinct
¶
一个布尔值,指定Filter是否在查询集上使用distinct。
使用跨越关系的过滤器时,此选项可用于消除重复结果。 Defaults to False
.
exclude
¶
A boolean that specifies whether the Filter should use filter
or exclude
on the queryset. Defaults to False
.
**kwargs
¶
Any additional keyword arguments are stored as the extra
parameter on the
filter. They are provided to the accompanying form Field
and can be used to
provide arguments like choices
. Some field-related arguments:
widget
¶
django.form Widget类,它代表Filter
。 除了Django附带的小部件,你可以使用django-filter提供的其他小部件,它们可能很有用:
- LinkWidget – this displays the options in a manner similar to the way the Django Admin does, as a series of links. The link for the selected option will have
class="selected"
.- BooleanWidget – this widget converts its input into Python’s True/False values. It will convert all case variations of
True
andFalse
into the internal Python values.- CSVWidget – this widget expects a comma separated value and converts it into a list of string values. It is expected that the field class handle a list of values as well as type conversion.
- RangeWidget – this widget is used with
RangeFilter
to generate two form input elements using a single field.
ModelChoiceFilter和ModelMultipleChoiceFilter参数¶
These arguments apply specifically to ModelChoiceFilter and ModelMultipleChoiceFilter only.
queryset
¶
ModelChoiceFilter
and ModelMultipleChoiceFilter
require a queryset to
operate on which must be passed as a kwarg.
to_field_name
¶
If you pass in to_field_name
(which gets forwarded to the Django field),
it will be used also in the default get_filter_predicate
implementation
as the model’s attribute.
Filters¶
CharFilter
¶
This filter does simple character matches, used with CharField
and
TextField
by default.
UUIDFilter
¶
This filter matches UUID values, used with models.UUIDField
by default.
BooleanFilter
¶
This filter matches a boolean, either True
or False
, used with
BooleanField
and NullBooleanField
by default.
ChoiceFilter
¶
This filter matches values in its choices
argument. The choices
must be
explicitly passed when the filter is declared on the FilterSet
. For example,
class User(models.Model):
username = models.CharField(max_length=255)
first_name = SubCharField(max_length=100)
last_name = SubSubCharField(max_length=100)
status = models.IntegerField(choices=STATUS_CHOICES, default=0)
STATUS_CHOICES = (
(0, 'Regular'),
(1, 'Manager'),
(2, 'Admin'),
)
class F(FilterSet):
status = ChoiceFilter(choices=STATUS_CHOICES)
class Meta:
model = User
fields = ['status']
ChoiceFilter
also has arguments that enable a choice for not filtering, as
well as a choice for filtering by None
values. Each of the arguments have a
corresponding global setting (Settings Reference).
empty_label
: The display label to use for the select choice to not filter. The choice may be disabled by setting this argument toNone
. Defaults toFILTERS_EMPTY_CHOICE_LABEL
.null_label
: The display label to use for the choice to filter byNone
values. The choice may be disabled by setting this argument toNone
. Defaults toFILTERS_NULL_CHOICE_LABEL
.null_value
: The special value to match to enable filtering byNone
values. This value defaultsFILTERS_NULL_CHOICE_VALUE
and needs to be a non-empty value (''
,None
,[]
,()
,{}
).
TypedChoiceFilter
¶
The same as ChoiceFilter
with the added possibility to convert value to
match against. This could be done by using coerce parameter.
An example use-case is limiting boolean choices to match against so only
some predefined strings could be used as input of a boolean filter:
import django_filters
from distutils.util import strtobool
BOOLEAN_CHOICES = (('false', 'False'), ('true', 'True'),)
class YourFilterSet(django_filters.FilterSet):
...
flag = django_filters.TypedChoiceFilter(choices=BOOLEAN_CHOICES,
coerce=strtobool)
MultipleChoiceFilter
¶
The same as ChoiceFilter
except the user can select multiple choices
and the filter will form the OR of these choices by default to match items.
The filter will form the AND of the selected choices when the conjoined=True
argument is passed to this class.
Multiple choices are represented in the query string by reusing the same key with different values (e.g. ‘’?status=Regular&status=Admin’‘).
distinct
defaults to True
as to-many relationships will generally require this.
Advanced Use: Depending on your application logic, when all or no choices are selected, filtering may be a noop. In this case you may wish to avoid the filtering overhead, particularly of the distinct call.
Set always_filter to False after instantiation to enable the default is_noop test.
Override is_noop if you require a different test for your application.
TypedMultipleChoiceFilter
¶
Like MultipleChoiceFilter
, but in addition accepts the coerce
parameter, as
in TypedChoiceFilter
.
DateFilter
¶
Matches on a date. Used with DateField
by default.
TimeFilter
¶
Matches on a time. Used with TimeField
by default.
DateTimeFilter
¶
Matches on a date and time. Used with DateTimeField
by default.
IsoDateTimeFilter
¶
Uses IsoDateTimeField
to support filtering on ISO 8601 formatted dates, as are often
used in APIs, and are employed by default by Django REST Framework.
Example:
class F(FilterSet):
"""Filter for Books by date published, using ISO 8601 formatted dates"""
published = IsoDateTimeFilter()
class Meta:
model = Book
fields = ['published']
DurationFilter
¶
Matches on a duration. Used with DurationField
by default.
Supports both Django (‘%d %H:%M:%S.%f’) and ISO 8601 formatted durations (but only the sections that are accepted by Python’s timedelta, so no year, month, and week designators, e.g. ‘P3DT10H22M’).
ModelChoiceFilter
¶
Similar to a ChoiceFilter
except it works with related models, used for
ForeignKey
by default.
If automatically instantiated, ModelChoiceFilter
will use the default
QuerySet
for the related field. If manually instantiated you must
provide the queryset
kwarg.
Example:
class F(FilterSet):
"""Filter for books by author"""
author = ModelChoiceFilter(queryset=Author.objects.all())
class Meta:
model = Book
fields = ['author']
The queryset
argument also supports callable behavior. If a callable is
passed, it will be invoked with Filterset.request
as its only argument.
This allows you to easily filter by properties on the request object without
having to override the FilterSet.__init__
.
Note
You should expect that the request object may be None.
def departments(request):
if request is None:
return Department.objects.none()
company = request.user.company
return company.department_set.all()
class EmployeeFilter(filters.FilterSet):
department = filters.ModelChoiceFilter(queryset=departments)
...
ModelMultipleChoiceFilter
¶
Similar to a MultipleChoiceFilter
except it works with related models, used
for ManyToManyField
by default.
As with ModelChoiceFilter
, if automatically instantiated,
ModelMultipleChoiceFilter
will use the default QuerySet
for the related
field. If manually instantiated you must provide the queryset
kwarg.
Like ModelChoiceFilter
, the queryset
argument has callable behavior.
To use a custom field name for the lookup, you can use to_field_name
:
class FooFilter(BaseFilterSet):
foo = django_filters.filters.ModelMultipleChoiceFilter(
field_name='attr__uuid',
to_field_name='uuid',
queryset=Foo.objects.all(),
)
If you want to use a custom queryset, e.g. to add annotated fields, this can be done as follows:
class MyMultipleChoiceFilter(django_filters.ModelMultipleChoiceFilter):
def get_filter_predicate(self, v):
return {'annotated_field': v.annotated_field}
def filter(self, qs, value):
if value:
qs = qs.annotate_with_custom_field()
qs = super().filter(qs, value)
return qs
foo = MyMultipleChoiceFilter(
to_field_name='annotated_field',
queryset=Model.objects.annotate_with_custom_field(),
)
The annotate_with_custom_field
method would be defined through a custom
QuerySet, which then gets used as the model’s manager:
class CustomQuerySet(models.QuerySet):
def annotate_with_custom_field(self):
return self.annotate(
custom_field=Case(
When(foo__isnull=False,
then=F('foo__uuid')),
When(bar__isnull=False,
then=F('bar__uuid')),
default=None,
),
)
class MyModel(models.Model):
objects = CustomQuerySet.as_manager()
NumberFilter
¶
Filters based on a numerical value, used with IntegerField
, FloatField
,
and DecimalField
by default.
NumericRangeFilter
¶
Filters where a value is between two numerical values, or greater than a minimum or less
than a maximum where only one limit value is provided. This filter is designed to work
with the Postgres Numerical Range Fields, including IntegerRangeField
,
BigIntegerRangeField
and FloatRangeField
(available since Django 1.8). The default
widget used is the RangeField
.
Regular field lookups are available in addition to several containment lookups, including
overlap
, contains
, and contained_by
. More details in the Django docs.
If the lower limit value is provided, the filter automatically defaults to startswith
as the lookup and endswith
if only the upper limit value is provided.
RangeFilter
¶
Filters where a value is between two numerical values, or greater than a minimum or less than a maximum where only one limit value is provided.
class F(FilterSet):
"""Filter for Books by Price"""
price = RangeFilter()
class Meta:
model = Book
fields = ['price']
qs = Book.objects.all().order_by('title')
# Range: Books between 5€ and 15€
f = F({'price_min': '5', 'price_max': '15'}, queryset=qs)
# Min-Only: Books costing more the 11€
f = F({'price_min': '11'}, queryset=qs)
# Max-Only: Books costing less than 19€
f = F({'price_max': '19'}, queryset=qs)
DateRangeFilter
¶
Filter similar to the admin changelist date one, it has a number of common selections for working with date fields.
DateFromToRangeFilter
¶
Similar to a RangeFilter
except it uses dates instead of numerical values. It can be used with DateField
. It also works with DateTimeField
, but takes into consideration only the date.
Example of using the DateField
field:
class Comment(models.Model):
date = models.DateField()
time = models.TimeField()
class F(FilterSet):
date = DateFromToRangeFilter()
class Meta:
model = Comment
fields = ['date']
# Range: Comments added between 2016-01-01 and 2016-02-01
f = F({'date_after': '2016-01-01', 'date_before': '2016-02-01'})
# Min-Only: Comments added after 2016-01-01
f = F({'date_after': '2016-01-01'})
# Max-Only: Comments added before 2016-02-01
f = F({'date_before': '2016-02-01'})
Note
When filtering ranges that occurs on DST transition dates DateFromToRangeFilter
will use the first valid hour of the day for start datetime and the last valid hour of the day for end datetime.
This is OK for most applications, but if you want to customize this behavior you must extend DateFromToRangeFilter
and make a custom field for it.
Warning
If you’re using Django prior to 1.9 you may hit AmbiguousTimeError
or NonExistentTimeError
when start/end date matches DST start/end respectively.
This occurs because versions before 1.9 don’t allow to change the DST behavior for making a datetime aware.
Example of using the DateTimeField
field:
class Article(models.Model):
published = models.DateTimeField()
class F(FilterSet):
published = DateFromToRangeFilter()
class Meta:
model = Article
fields = ['published']
Article.objects.create(published='2016-01-01 8:00')
Article.objects.create(published='2016-01-20 10:00')
Article.objects.create(published='2016-02-10 12:00')
# Range: Articles published between 2016-01-01 and 2016-02-01
f = F({'published_after': '2016-01-01', 'published_before': '2016-02-01'})
assert len(f.qs) == 2
# Min-Only: Articles published after 2016-01-01
f = F({'published_after': '2016-01-01'})
assert len(f.qs) == 3
# Max-Only: Articles published before 2016-02-01
f = F({'published_before': '2016-02-01'})
assert len(f.qs) == 2
DateTimeFromToRangeFilter
¶
Similar to a RangeFilter
except it uses datetime format values instead of numerical values. It can be used with DateTimeField
.
Example:
class Article(models.Model):
published = models.DateTimeField()
class F(FilterSet):
published = DateTimeFromToRangeFilter()
class Meta:
model = Article
fields = ['published']
Article.objects.create(published='2016-01-01 8:00')
Article.objects.create(published='2016-01-01 9:30')
Article.objects.create(published='2016-01-02 8:00')
# Range: Articles published 2016-01-01 between 8:00 and 10:00
f = F({'published_after': '2016-01-01 8:00', 'published_before': '2016-01-01 10:00'})
assert len(f.qs) == 2
# Min-Only: Articles published after 2016-01-01 8:00
f = F({'published_after': '2016-01-01 8:00'})
assert len(f.qs) == 3
# Max-Only: Articles published before 2016-01-01 10:00
f = F({'published_before': '2016-01-01 10:00'})
assert len(f.qs) == 2
IsoDateTimeFromToRangeFilter
¶
Similar to a RangeFilter
except it uses ISO 8601 formatted values instead of numerical values. It can be used with IsoDateTimeField
.
Example:
class Article(models.Model):
published = dajngo_filters.IsoDateTimeField()
class F(FilterSet):
published = IsoDateTimeFromToRangeFilter()
class Meta:
model = Article
fields = ['published']
Article.objects.create(published='2016-01-01T8:00:00+01:00')
Article.objects.create(published='2016-01-01T9:30:00+01:00')
Article.objects.create(published='2016-01-02T8:00:00+01:00')
# Range: Articles published 2016-01-01 between 8:00 and 10:00
f = F({'published_after': '2016-01-01T8:00:00+01:00', 'published_before': '2016-01-01T10:00:00+01:00'})
assert len(f.qs) == 2
# Min-Only: Articles published after 2016-01-01 8:00
f = F({'published_after': '2016-01-01T8:00:00+01:00'})
assert len(f.qs) == 3
# Max-Only: Articles published before 2016-01-01 10:00
f = F({'published_before': '2016-01-01T10:00:00+0100'})
assert len(f.qs) == 2
TimeRangeFilter
¶
Similar to a RangeFilter
except it uses time format values instead of numerical values. It can be used with TimeField
.
Example:
class Comment(models.Model):
date = models.DateField()
time = models.TimeField()
class F(FilterSet):
time = TimeRangeFilter()
class Meta:
model = Comment
fields = ['time']
# Range: Comments added between 8:00 and 10:00
f = F({'time_after': '8:00', 'time_before': '10:00'})
# Min-Only: Comments added after 8:00
f = F({'time_after': '8:00'})
# Max-Only: Comments added before 10:00
f = F({'time_before': '10:00'})
AllValuesFilter
¶
This is a ChoiceFilter
whose choices are the current values in the
database. So if in the DB for the given field you have values of 5, 7, and 9
each of those is present as an option. This is similar to the default behavior
of the admin.
AllValuesMultipleFilter
¶
This is a MultipleChoiceFilter
whose choices are the current values in the
database. So if in the DB for the given field you have values of 5, 7, and 9
each of those is present as an option. This is similar to the default behavior
of the admin.
LookupChoiceFilter
¶
A combined filter that allows users to select the lookup expression from a dropdown.
lookup_choices
is an optional argument that accepts multiple input formats, and is ultimately normalized as the choices used in the lookup dropdown. See.get_lookup_choices()
for more information.field_class
is an optional argument that allows you to set the inner form field class used to validate the value. Default:forms.CharField
ex:
price = django_filters.LookupChoiceFilter(
field_class=forms.DecimalField,
lookup_choices=[
('exact', 'Equals'),
('gt', 'Greater than'),
('lt', 'Less than'),
]
)
BaseInFilter
¶
This is a base class used for creating IN lookup filters. It is expected that this filter class is used in conjunction with another filter class, as this class only validates that the incoming value is comma-separated. The secondary filter is then used to validate the individual values.
Example:
class NumberInFilter(BaseInFilter, NumberFilter):
pass
class F(FilterSet):
id__in = NumberInFilter(field_name='id', lookup_expr='in')
class Meta:
model = User
User.objects.create(username='alex')
User.objects.create(username='jacob')
User.objects.create(username='aaron')
User.objects.create(username='carl')
# In: User with IDs 1 and 3.
f = F({'id__in': '1,3'})
assert len(f.qs) == 2
BaseRangeFilter
¶
This is a base class used for creating RANGE lookup filters. It behaves
identically to BaseInFilter
with the exception that it expects only two
comma-separated values.
Example:
class NumberRangeFilter(BaseRangeFilter, NumberFilter):
pass
class F(FilterSet):
id__range = NumberRangeFilter(field_name='id', lookup_expr='range')
class Meta:
model = User
User.objects.create(username='alex')
User.objects.create(username='jacob')
User.objects.create(username='aaron')
User.objects.create(username='carl')
# Range: User with IDs between 1 and 3.
f = F({'id__range': '1,3'})
assert len(f.qs) == 3
OrderingFilter
¶
Enable queryset ordering. As an extension of ChoiceFilter
it accepts
two additional arguments that are used to build the ordering choices.
fields
is a mapping of {model field name: parameter name}. The parameter names are exposed in the choices and mask/alias the field names used in theorder_by()
call. Similar to fieldchoices
,fields
accepts the ‘list of two-tuples’ syntax that retains order.fields
may also just be an iterable of strings. In this case, the field names simply double as the exposed parameter names.field_labels
is an optional argument that allows you to customize the display label for the corresponding parameter. It accepts a mapping of {field name: human readable label}. Keep in mind that the key is the field name, and not the exposed parameter name.
class UserFilter(FilterSet):
account = CharFilter(field_name='username')
status = NumberFilter(field_name='status')
o = OrderingFilter(
# tuple-mapping retains order
fields=(
('username', 'account'),
('first_name', 'first_name'),
('last_name', 'last_name'),
),
# labels do not need to retain order
field_labels={
'username': 'User account',
}
)
class Meta:
model = User
fields = ['first_name', 'last_name']
>>> UserFilter().filters['o'].field.choices
[
('account', 'User account'),
('-account', 'User account (descending)'),
('first_name', 'First name'),
('-first_name', 'First name (descending)'),
('last_name', 'Last name'),
('-last_name', 'Last name (descending)'),
]
Additionally, you can just provide your own choices
if you require
explicit control over the exposed options. For example, when you might
want to disable descending sort options.
class UserFilter(FilterSet):
account = CharFilter(field_name='username')
status = NumberFilter(field_name='status')
o = OrderingFilter(
choices=(
('account', 'Account'),
),
fields={
'username': 'account',
},
)
This filter is also CSV-based, and accepts multiple ordering params. The
default select widget does not enable the use of this, but it is useful
for APIs. SelectMultiple
widgets are not compatible, given that they
are not able to retain selection order.
Adding Custom filter choices¶
If you wish to sort by non-model fields, you’ll need to add custom handling to an
OrderingFilter
subclass. For example, if you want to sort by a computed
‘relevance’ factor, you would need to do something like the following:
class CustomOrderingFilter(django_filters.OrderingFilter):
def __init__(self, *args, **kwargs):
super(CustomOrderingFilter, self).__init__(*args, **kwargs)
self.extra['choices'] += [
('relevance', 'Relevance'),
('-relevance', 'Relevance (descending)'),
]
def filter(self, qs, value):
# OrderingFilter is CSV-based, so `value` is a list
if any(v in ['relevance', '-relevance'] for v in value):
# sort queryset by relevance
return ...
return super(CustomOrderingFilter, self).filter(qs, value)
Field Reference¶
IsoDateTimeField
¶
Extends django.forms.DateTimeField
to allow parsing ISO 8601 formated dates, in addition to existing formats
Defines a class level attribute ISO_8601
as constant for the format.
Sets input_formats = [ISO_8601]
— this means that by default IsoDateTimeField
will only parse ISO 8601 formated dates.
You may set input_formats
to your list of required formats as per the DateTimeField Docs, using the ISO_8601
class level attribute to specify the ISO 8601 format.
f = IsoDateTimeField()
f.input_formats = [IsoDateTimeField.ISO_8601] + DateTimeField.input_formats
Widget Reference¶
This is a reference document with a list of the provided widgets and their arguments.
LinkWidget
¶
This widget renders each option as a link, instead of an actual <input>. It has
one method that you can override for additional customizability.
option_string()
should return a string with 3 Python keyword argument
placeholders:
attrs
: This is a string with all the attributes that will be on the final<a>
tag.query_string
: This is the query string for use in thehref
option on the<a>
element.label
: This is the text to be displayed to the user.
BooleanWidget
¶
This widget converts its input into Python’s True/False values. It will convert
all case variations of True
and False
into the internal Python values.
To use it, pass this into the widgets
argument of the BooleanFilter
:
active = BooleanFilter(widget=BooleanWidget())
CSVWidget
¶
This widget expects a comma separated value and converts it into a list of string values. It is expected that the field class handle a list of values as well as type conversion.
RangeWidget
¶
This widget is used with RangeFilter
and its subclasses. It generates two
form input elements which generally act as start/end values in a range.
Under the hood, it is Django’s forms.TextInput
widget and excepts
the same arguments and values. To use it, pass it to widget
argument of
a RangeField
:
date_range = DateFromToRangeFilter(widget=RangeWidget(attrs={'placeholder': 'YYYY/MM/DD'}))
SuffixedMultiWidget
¶
Extends Django’s builtin MultiWidget
to append custom suffixes instead of
indices. For example, take a range widget that accepts minimum and maximum
bounds. By default, the resulting query params would look like the following:
GET /products?price_0=10&price_1=25 HTTP/1.1
By using SuffixedMultiWidget
instead, you can provide human-friendly suffixes.
class RangeWidget(SuffixedMultiWidget):
suffixes = ['min', 'max']
The query names are now a little more ergonomic.
GET /products?price_min=10&price_max=25 HTTP/1.1
Settings Reference¶
Here is a list of all available settings of django-filters and their
default values. All settings are prefixed with FILTERS_
, although this
is a bit verbose it helps to make it easy to identify these settings.
FILTERS_EMPTY_CHOICE_LABEL¶
Default: '---------'
Set the default value for ChoiceFilter.empty_label
. You may disable the empty choice by setting this to None
.
FILTERS_NULL_CHOICE_LABEL¶
Default: None
Set the default value for ChoiceFilter.null_label
. You may enable the null choice by setting a non-None
value.
FILTERS_NULL_CHOICE_VALUE¶
Default: 'null'
Set the default value for ChoiceFilter.null_value
. You may want to change this value if the default 'null'
string conflicts with an actual choice.
FILTERS_DISABLE_HELP_TEXT¶
Default: False
Some filters provide informational help_text
. For example, csv-based
filters (filters.BaseCSVFilter
) inform users that “Multiple values may
be separated by commas”.
You may set this to True
to disable the help_text
for all
filters, removing the text from the rendered form’s output.
FILTERS_VERBOSE_LOOKUPS¶
Note
This is considered an advanced setting and is subject to change.
Default:
# refer to 'django_filters.conf.DEFAULTS'
'VERBOSE_LOOKUPS': {
'exact': _(''),
'iexact': _(''),
'contains': _('contains'),
'icontains': _('contains'),
...
}
This setting controls the verbose output for generated filter labels. Instead of getting expression parts such as “lt” and “contained_by”, the verbose label would contain “is less than” and “is contained by”. Verbose output may be disabled by setting this to a falsy value.
This setting also accepts callables. The callable should not require arguments and should return a dictionary. This is useful for extending or overriding the default terms without having to copy the entire set of terms to your settings. For example, you could add verbose output for “exact” lookups.
# settings.py
def FILTERS_VERBOSE_LOOKUPS():
from django_filters.conf import DEFAULTS
verbose_lookups = DEFAULTS['VERBOSE_LOOKUPS'].copy()
verbose_lookups.update({
'exact': 'is equal to',
})
return verbose_lookups
Running the Test Suite¶
运行django-filter测试的最简单方法是查看源代码并创建一个virtualenv,您可以在其中安装测试依赖项。 Django-filter使用自定义测试运行器来配置环境,因此可以使用包装器脚本来设置和运行测试套件。
Note
The following assumes you have virtualenv and git installed.
Clone the repository¶
Get the source code using the following command:
$ git clone https://github.com/carltongibson/django-filter.git
Switch to the django-filter directory:
$ cd django-filter
Set up the virtualenv¶
Create a new virtualenv to run the test suite in:
$ virtualenv venv
Then activate the virtualenv and install the test requirements:
$ source venv/bin/activate
$ pip install -r requirements/test.txt
Test all supported versions¶
You can also use the excellent tox testing tool to run the tests against all supported versions of Python and Django. Install tox, and then simply run:
$ pip install tox
$ tox
Housekeeping¶
The isort
utility is used to maintain module imports. You can either test
the module imports with the appropriate tox env, or with isort directly.
$ pip install tox
$ tox -e isort
# or
$ pip install isort
$ isort --check-only --recursive django_filters tests
To sort the imports, simply remove the --check-only
option.
$ isort --recursive django_filters tests