DRF Dynamic Fields
drf-dynamic-fields is a lightweight Django REST Framework utility that enables serializers to dynamically expose a subset of their fields based on query parameters in the API request. This can be useful for reducing payload size and tailoring responses for different client needs. The current version is 0.4.0, and releases are infrequent, reflecting its stable and focused scope.
Common errors
-
KeyError: 'request'
cause The `DynamicFieldsMixin` tries to access `self.context['request']` but the serializer was instantiated without the request in its context.fixEnsure your view passes the request object in the serializer context, e.g., `serializer = MySerializer(instance, context={'request': request})`. -
Serializer output does not reflect `fields` or `omit` query parameters.
cause The `DynamicFieldsMixin` is either not inherited by the serializer, or the `request` object is missing from the serializer's context.fixVerify that `DynamicFieldsMixin` is the first base class (after `serializers.ModelSerializer`) for your serializer, and confirm that your view passes `request` in the serializer's context dictionary. -
ValueError: Field 'invalid_field_name' does not exist on serializer 'MySerializer'
cause A field name specified in the `fields` or `omit` query parameter does not correspond to an actual field defined on the serializer.fixCheck for typos in the query parameter's field names. Ensure that all requested fields are present in the serializer's `Meta.fields` or are explicitly defined on the serializer.
Warnings
- gotcha The `DynamicFieldsMixin` relies on the `request` object being present in the serializer's `context`. If you manually instantiate a serializer (e.g., in tests or custom logic) without providing `context={'request': request}`, dynamic field selection will not work and might raise a `KeyError`.
- gotcha If both `fields` and `omit` query parameters are provided, `drf-dynamic-fields` will prioritize `omit`. Fields listed in `omit` will always be removed, even if they are also listed in `fields`.
- gotcha While `drf-dynamic-fields` effectively reduces the API response payload, it primarily affects the *serialization* stage. The underlying database query (ORM) might still fetch all columns for the model, leading to potential performance issues if your serializer includes many heavy fields or related objects that are then filtered out.
Install
-
pip install drf-dynamic-fields
Imports
- DynamicFieldsMixin
from drf_dynamic_fields import DynamicFieldsMixin
Quickstart
from rest_framework import serializers, viewsets
from drf_dynamic_fields import DynamicFieldsMixin
from django.db import models
# --- Example Django Model ---
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10, decimal_places=2)
is_available = models.BooleanField(default=True)
def __str__(self):
return self.name
# --- DRF Serializer with DynamicFieldsMixin ---
class ProductSerializer(DynamicFieldsMixin, serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id', 'name', 'description', 'price', 'is_available']
# --- DRF ViewSet ---
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
# To use this, configure Django URL patterns to include ProductViewSet.
# Example API request with dynamic fields:
# GET /api/products/?fields=id,name,price
# GET /api/products/?omit=description,is_available