过滤器
API 参考:Filters¶
过滤器负责把查询参数转换成 Tortoise 的 Q 表达式或 filter() 调用。ListModelMixin.list() 会按 filter_class 的顺序依次执行。使用说明见 过滤。
默认过滤器与参数¶
settings.DEFAULT_FILTERS 的顺序是 SearchFilter、JsonLogicFilter、QueryParamFilter、OrderingFactory,因此以下参数可以同时使用:
| 参数 | 过滤器 | 作用 |
|---|---|---|
search |
SearchFilter |
多字段模糊搜索 |
filter |
JsonLogicFilter |
JSON Logic 表达式 |
ordering |
OrderingFactory |
排序 |
任意 filter_fields 中的键 |
QueryParamFilter |
精确匹配 |
字段白名单来自 ViewSet 的类属性:
from srf.views import BaseViewSet
class BookViewSet(BaseViewSet):
search_fields = ["title", "author"]
# 别名 -> ORM 字段
filter_fields = {"published": "is_published", "author_id": "author__id"}
ordering_fields = ["create_time", "title"]
列表会被当作“字段名即参数名”,字典则用于把外部参数名映射到内部 ORM 字段。
过滤器类¶
四个内置过滤器都继承 BaseFilter,通过类属性声明各自需要的白名单字段。
BaseFilter ¶
Bases: ABC
Base class for all filters.
Subclasses must set cls_fields to the name of the view attribute holding the
field configuration (e.g. "search_fields"); missing it raises TypeError
at class-definition time.
Attributes:
| Name | Type | Description |
|---|---|---|
cls_fields |
str | None
|
Name of the view attribute that lists the allowed fields. |
view_class |
The view instance this filter is bound to. |
|
filter_fields |
Resolved field mapping. A list config becomes |
子类必须设置 cls_fields(取值为 ViewSet 上保存字段白名单的属性名),否则在类定义阶段就会抛出 TypeError。filter_fields 在实例化时被归一化为 {字段: ORM 字段} 的字典。
SearchFilter ¶
Bases: BaseFilter
Keyword filter applicable to common ORM (example uses TortoiseORM syntax).
Reads the search query parameter, splits it on whitespace, and matches each
term against every configured field with __icontains: terms are AND-ed,
fields are OR-ed.
?search=alice admin 的语义:
- 按空白切分成多个关键词;
- 每个关键词在所有字段之间用 OR 匹配(
__icontains); - 多个关键词之间用 AND 组合。
JsonLogicFilter ¶
Bases: BaseFilter
Filter driven by a JSON expression in the filter query parameter.
Supports operators ==, !=, >, >=, <, <=, in, not in,
like (icontains) and nested and / or / not. Only fields listed in
the view's filter_fields are usable; anything else is ignored.
Attributes:
| Name | Type | Description |
|---|---|---|
OPERATOR_MAP |
dict[str, Callable]
|
Mapping of JSON-logic operators to |
DOCS_URL |
str
|
Documentation URL included in every 400 response message. |
OPERATOR_MAP
class-attribute
¶
OPERATOR_MAP: dict[str, Callable] = {'==': lambda k, v: Q(**{k: v}), '!=': lambda k, v: ~Q(**{k: v}), '!': lambda k, v: ~Q(**{k: v}), '>': lambda k, v: Q(**{f'{k}__gt': v}), '>=': lambda k, v: Q(**{f'{k}__gte': v}), '<': lambda k, v: Q(**{f'{k}__lt': v}), '<=': lambda k, v: Q(**{f'{k}__lte': v}), 'in': lambda k, v: Q(**{f'{k}__in': v}), 'not in': lambda k, v: ~Q(**{f'{k}__in': v}), 'like': lambda k, v: Q(**{f'{k}__icontains': v})}
?filter= 接收一段 JSON Logic 表达式,支持的操作符:
| 操作符 | 含义 | 生成的查询 |
|---|---|---|
== |
等于 | field=value |
!= / ! |
不等于 | NOT field=value |
> |
大于 | field__gt |
>= |
大于等于 | field__gte |
< |
小于 | field__lt |
<= |
小于等于 | field__lte |
in |
属于 | field__in |
not in |
不属于 | NOT field__in |
like |
包含 | field__icontains |
组合规则:
and/or的参数是__表达式数组__;not的参数是单个表达式;- 字段必须出现在
filter_fields中,否则该条件被忽略; - JSON 无法解析时返回
400 Bad Request。
# ?filter=<urlencoded JSON>
{
"and": [
{"==": [{"var": "published"}, True]},
{"like": [{"var": "title"}, "python"]},
]
}
QueryParamFilter ¶
Bases: BaseFilter
Exact-match filter based on query parameters.
A query parameter is applied only when its name exactly matches a key of the view's
filter_fields. A repeated parameter (?a=1&a=2) becomes an __in lookup,
a single value becomes an exact match.
参数名必须与 filter_fields 的键完全一致:
- 单值:
?published=true→ 精确匹配; - 重复参数:
?id=1&id=2→id__in=[1, 2]。
不在白名单中的参数会被忽略,不会报错。
OrderingFactory ¶
Bases: BaseFilter
Ordering filter driven by the ordering query parameter.
Accepts a comma-separated list such as ?ordering=name,-create_time; fields not
listed in the view's ordering_fields are silently ignored.
?ordering=-create_time,title:逗号分隔,前缀 - 表示倒序。未出现在 ordering_fields 中的字段会被忽略;所有字段都无效时保持默认顺序。