Introduction¶
What is rest-filters?¶
rest-filters is an extension for Django REST Framework that parses query
parameters and constructs the corresponding QuerySet objects. It serves as
a replacement for the commonly used django-filter library.
Key features¶
rest-filters is specifically designed to be used in a REST API context. You
can enforce strict constraints on your parameters, how they are provided and
how they interact with each other. Here are some key features:
Use serializer fields to parse query parameters. Existing serializer fields used in request bodies can be reused, providing consistency in parsing logic and validation error messages. This also simplifies the implementation of custom fields by utilizing familiar serializer API.
Support for default values on filter fields is built-in. Defaults can be static or dynamically computed at runtime.
Use filter groups to combine related query components (e.g., using logical operators such as OR, AND). Filter groups provide a flexible mechanism for expressing arbitrary boolean logic within filters, allowing for more precise query construction.
Utilize the constraint system to define and enforce rules between independent filters. Built-in support is provided for common use cases such as mutual exclusivity and mutual inclusivity. Custom constraints can be implemented to enforce arbitrary validation logic across filters.
Define child filters to inherit behavior from parent filters, simplifying the creation of closely related filters. For example, filters like
created.gte,created.lte, orcreated.yearcan be implemented with ease. Child filters also allow traversing relationships via foreign keys, enabling expressions such ascompany.industry.name.Use the serializer context to dynamically modify filter behavior at runtime. Filters can be added or removed based on conditions such as user permissions. Additionally, reusable filter fields can be implemented to encapsulate permission checks and other dynamic logic.
Annotations can be added directly to the
QuerySetwithin the filter definition. This enables the creation of filters based on simple annotations without the need to implement method-based filters.By default, a
ValidationErroris raised when a user submits an unrecognized query parameter. If closely matching parameter names are detected, the error message will provide suggestions to guide the user in a self-documenting manner. This behavior is configurable and can be disabled if desired.Query parameter names can be customized freely. You don’t need to stick with Python identifiers.