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 ¶
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. |
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 ¶
Validate query parameters and return cleaned data as a dictionary.
Raises:
| Type | Description |
|---|---|
ValidationError
|
If validation fails. |
filter_queryset ¶
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. |