Filters
API Reference: Filters¶
Filters convert query parameters into Tortoise Q expressions or filter() calls. ListModelMixin.list() runs them in the order of filter_class. See Filtering for usage.
Default filters and parameters¶
settings.DEFAULT_FILTERS has the order SearchFilter, JsonLogicFilter, QueryParamFilter, OrderingFactory, so the following parameters can be used together:
| Parameter | Filter | Purpose |
|---|---|---|
search |
SearchFilter |
Fuzzy search across multiple fields |
filter |
JsonLogicFilter |
JSON Logic expressions |
ordering |
OrderingFactory |
Sorting |
Any key in filter_fields |
QueryParamFilter |
Exact matching |
The field allowlists come from ViewSet class attributes:
from srf.views import BaseViewSet
class BookViewSet(BaseViewSet):
search_fields = ["title", "author"]
# alias -> ORM field
filter_fields = {"published": "is_published", "author_id": "author__id"}
ordering_fields = ["create_time", "title"]
Lists are treated as "the field name is the parameter name", while dictionaries map external parameter names to internal ORM fields.
Filter classes¶
All four built-in filters inherit from BaseFilter and declare the allowlist fields they need through class attributes.
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 |
Subclasses must set cls_fields (the name of the ViewSet attribute that stores the field allowlist); otherwise a TypeError is raised at class definition time. filter_fields is normalized at instantiation into a {field: ORM field} dictionary.
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.
Semantics of ?search=alice admin:
- Split into multiple keywords by whitespace;
- Each keyword is matched across all fields with OR (
__icontains); - Multiple keywords are combined with 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= accepts a JSON Logic expression. Supported operators:
| Operator | Meaning | Generated query |
|---|---|---|
== |
Equals | field=value |
!= / ! |
Not equals | NOT field=value |
> |
Greater than | field__gt |
>= |
Greater than or equal | field__gte |
< |
Less than | field__lt |
<= |
Less than or equal | field__lte |
in |
In | field__in |
not in |
Not in | NOT field__in |
like |
Contains | field__icontains |
Combination rules:
- The arguments of
and/orare an array of expressions; - The argument of
notis a single expression; - Fields must appear in
filter_fields; otherwise the condition is ignored; - If the JSON cannot be parsed,
400 Bad Requestis returned.
# ?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.
Parameter names must exactly match the keys of filter_fields:
- Single value:
?published=trueβ exact match; - Repeated parameter:
?id=1&id=2βid__in=[1, 2].
Parameters not in the allowlist are ignored and do not raise an error.
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: comma-separated; a - prefix means descending. Fields not present in ordering_fields are ignored; if all fields are invalid, the default order is kept.