Registry / web-framework / drf-flex-fields

drf-flex-fields

JSON →
library1.0.2pypypiunverified

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-fields
INSTALL
IMPORT
SIG · DRF-FLEX-FIELDS
D
drf-flex-fields
web-frameworkpythonv1.0.2
Install
2.4s avg
Import
—
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v1.0.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.920 runs
installs and imports cleanly · install 0.0s · import 0.000s · 19.3MB
glibc
py 3.10–3.920 runs
installs and imports cleanly · install 2.4s · import 0.000s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

FlexFieldsModelSerializer
✓ from rest_flex_fields import FlexFieldsModelSerializer
✗ from rest_flex_fields import FlexFieldsModelSerializer

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.

import os from django.db import models from rest_framework import serializers, viewsets from rest_flex_fields import FlexFieldsModelSerializer from rest_flex_fields.views import FlexFieldsMixin # Minimal Django setup for demonstration os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') # Define a simple Django model (e.g., in models.py) class Country(models.Model): name = models.CharField(max_length=100) population = models.IntegerField() def __str__(self): return self.name class State(models.Model): name = models.CharField(max_length=100) country = models.ForeignKey(Country, related_name='states', on_delete=models.CASCADE) def __str__(self): return self.name # Define FlexFields serializers class StateSerializer(FlexFieldsModelSerializer): class Meta: model = State fields = ('id', 'name') class CountrySerializer(FlexFieldsModelSerializer): class Meta: model = Country fields = ('id', 'name', 'population', 'states') expandable_fields = { 'states': (StateSerializer, {'many': True}) } # Define a ViewSet using FlexFieldsMixin class CountryViewSet(FlexFieldsMixin, viewsets.ModelViewSet): queryset = Country.objects.all() serializer_class = CountrySerializer # Allow 'states' to be expanded on list views (GET /countries/) permit_list_expands = ['states'] # Example usage (conceptual, in a Django/DRF app context): # GET /countries/1/?expand=states # GET /countries/?fields=id,name
Debug
Known issues
gotchaBy default, expanding fields is only allowed on detail (single object) views to prevent accidental over-fetching on list views. To enable expansion on list views (e.g., `GET /items/?expand=related_field`), you must explicitly add the field name to `permit_list_expands` on your `FlexFieldsMixin` based ViewSet.
fix
Add `permit_list_expands = ['field_name']` to your `FlexFieldsMixin` based ViewSet's class definition.
affects: All versions
gotchaIf both `fields` and `expand` query parameters are used simultaneously, the `fields` parameter takes precedence. An expanded field will not be included in the response if it's not also explicitly listed in the `fields` parameter. This can lead to unexpected missing data if not understood.
fix
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`.
affects: All versions
gotchaUsing deep or recursive expansions (`?expand=a.b.c`) can result in a large number of database queries (`N+1` problem) and significantly impact performance. This is especially true without proper database query optimization.
fix
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.
affects: All versions
gotchaWhen referencing serializers by a string name (lazy evaluation) in `expandable_fields`, ensure you include the full app path (e.g., `'myapp.serializers.MySerializer'`) to avoid import resolution issues, especially with complex project structures or circular dependencies.
fix
Change `expandable_fields = {'field': ('MySerializer', {'many': True})}` to `expandable_fields = {'field': ('myapp.serializers.MySerializer', {'many': True})}`.
affects: All versions
gotchaThe `expand=*` or `expand=~all` wildcard options, while convenient, can expose the entire object graph and may lead to sensitive data exposure or performance degradation if not carefully controlled and restricted in a public API.
fix
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.
affects: All versions
Upgrade
Version history
1.0.2latest on PyPI · released Mar 11, 2023
Audit
Dependencies
djangorestframeworkrequiredCore dependency for Django REST Framework functionality.
djangorequiredUnderlying web framework.
Agent activity
8 hits · last 30 days
node
8
Resources
drf-flex-fields — pip install drf-flex-fields · libregistry