drf-flex-fields (DRF-FF) is a Python package for Django REST Framework that provides flexible, dynamic fields and nested resources for serializers. It allows clients to control which fields are included or excluded, and to dynamically expand related models via URL parameters like `?fields=id,name` or `?expand=organization.owner.roles`. The library focuses on simplicity with minimal entanglement with DRF's core classes. It is actively maintained with regular updates, including bug fixes and new features, as seen in the recent 1.0.x releases.
pip install drf-flex-fieldsVerified import paths — ran on the pinned version, not inferred.
To use `drf-flex-fields`, inherit your serializers from `FlexFieldsModelSerializer` and define `expandable_fields` in the `Meta` class. For viewsets, inherit from `FlexFieldsMixin` to enable query parameter processing. This allows dynamic field selection via `?fields=` and nested resource expansion via `?expand=` URL parameters. Remember to configure `permit_list_expands` on your viewset if you want to allow expansions on list endpoints, not just detail views.
Add `permit_list_expands = ['field_name']` to your `FlexFieldsMixin` based ViewSet's class definition.
Ensure that any fields you intend to expand are also included in the `fields` query parameter if you are using both. For example, `?fields=id,name,country&expand=country`.
Utilize `select_related()` and `prefetch_related()` in your ViewSet's `get_queryset()` method or configure the `FlexFieldsFilterBackend` to automatically optimize queries based on the `expand` parameter.
Change `expandable_fields = {'field': ('MySerializer', {'many': True})}` to `expandable_fields = {'field': ('myapp.serializers.MySerializer', {'many': True})}`.Avoid using wildcards in public APIs or implement strict permissioning and rate limiting. For internal/trusted APIs, ensure the performance implications are understood and mitigated.