Skip to content

FilterSet

The class that validates query parameters and applies filters to a Django queryset. See the FilterSet guide for an overview, Meta options, ordering, processors, validation, and PostgreSQL features.

FilterSet

FilterSet(
    data=None,
    request: Request | WSGIRequest | HttpRequest = None,
)

Bases: Serializer

A declarative way to filter Django querysets.

FilterSet extends rest_framework.serializers.Serializer to provide query parameter validation and queryset filtering. It supports type annotations, explicit field declarations, and automatic field generation from Django models. Fields automatically generate negation variants (e.g., "price!" for not equal), control via allow_negate property in fields. Lookup fields are generated from the lookups parameter (e.g., "price__gte"). Field priority: explicit declarations > type annotations > Meta.fields

Attributes:

Name Type Description
request Request

The DRF request object containing query parameters.

Meta Configuration

model (Model): Django model to filter. Required when using Meta.fields.

fields (Union[List[str], Tuple[str], Literal["all"]]): Fields to include. Use "all" to include all model fields or provide a list of field names. Explicitly declared fields take precedence over this setting.

exclude (Union[List[str], Tuple[str]]): Fields to exclude when using "all".

extra_kwargs (Dict[str, Dict]): Additional keyword arguments for fields.

required_fields (List[str]): Field names that should be marked as required.

order_param (str): Query parameter name for ordering. The default is "order_by".

order_fields (List[Tuple[str, str]]): Available ordering options as (query_value, model_field) tuples.

default_order_fields (List[str]): Default ordering when no order param is provided.

order_field_labels (List[Tuple[str, str]]): Human-readable labels for ordering options as (query_value, label) tuples.

override_order_direction (Literal["asc", "desc"]): Override Django's default ordering direction. Use "desc" to reverse the meaning of the "-" prefix. The default is "asc".

preprocessors (List[Callable[[FilterSet, QuerySet], QuerySet]]): Functions called before filtering. Each receives the filterset and queryset, returns queryset.

postprocessors (List[Callable[[FilterSet, QuerySet], QuerySet]]): Functions called after filtering. Each receives the filterset and queryset, returns queryset.

operator (Literal["AND", "OR", "XOR"]): Logical operator for combining filters. Default is "AND".

allow_negate (bool): Enables negation for fields (Only works for annotated fields and model fields).

lookup_separator (str): Default separator placed between a field name and its lookup variant suffix. Field-level lookup_separator overrides this, falls back to "__" when neither is set. Useful with alias-form lookups like {"max": "lte"} to produce price_max instead of price__max.

Methods:

Name Description
model_dump

Validates and returns cleaned query parameters as a dictionary.

filter_queryset

QuerySet) -> QuerySet: Applies validated filters to the queryset and returns filtered results.

Examples:

Using type annotations::

class ProductFilterSet(FilterSet):
    name: str
    price: int
    in_stock: bool

Using explicit field declarations::

from restflow.fields import StringField, IntegerField

class ProductFilterSet(FilterSet):
    name = StringField(lookups=["icontains"])
    price = IntegerField(lookups=["gte", "lte"])
    category = StringField(filter_by="category__name")

Using a Django model with Meta:

class ProductFilterSet(FilterSet):
    class Meta:
        model = Product
        fields = "__all__"
        order_fields = [("price", "price"), ("name", "name")]

In a view::

def list_products(request):
    queryset = Product.objects.all()
    filterset = ProductFilterSet(request=request)
    filtered_queryset = filterset.filter_queryset(queryset)
    return Response (data=list(filtered_queryset.values()))

model_dump

model_dump() -> dict[str, Any]

Validate query parameters and return cleaned data as a dictionary.

Raises:

Type Description
ValidationError

If validation fails.

filter_queryset

filter_queryset(queryset: QuerySet, ignore=None)

Apply validated filters to a queryset and return the filtered result.

This is the synchronous entry point. If any callable (method=, preprocessor, postprocessor) is async def, this raises TypeError pointing at afilter_queryset.

Parameters:

Name Type Description Default
queryset QuerySet

The Django queryset to filter.

required
ignore list[str]

List of field names to ignore. Defaults to None.

None

Returns: QuerySet: The filtered queryset after applying all filters and processors.

Raises:

Type Description
ValidationError

If query parameters fail validation.

TypeError

If a user-supplied callable returns a coroutine.

get_options

get_options()