{"id":9705,"library":"drf-dynamic-fields","title":"DRF Dynamic Fields","description":"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.","status":"active","version":"0.4.0","language":"en","source_language":"en","source_url":"https://github.com/dbrgn/drf-dynamic-fields","tags":["django","drf","rest-framework","serialization","fields","api"],"install":[{"cmd":"pip install drf-dynamic-fields","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"This library extends Django REST Framework serializers and views.","package":"djangorestframework","optional":false}],"imports":[{"symbol":"DynamicFieldsMixin","correct":"from drf_dynamic_fields import DynamicFieldsMixin"}],"quickstart":{"code":"from rest_framework import serializers, viewsets\nfrom drf_dynamic_fields import DynamicFieldsMixin\nfrom django.db import models\n\n# --- Example Django Model ---\nclass Product(models.Model):\n    name = models.CharField(max_length=100)\n    description = models.TextField()\n    price = models.DecimalField(max_digits=10, decimal_places=2)\n    is_available = models.BooleanField(default=True)\n\n    def __str__(self):\n        return self.name\n\n# --- DRF Serializer with DynamicFieldsMixin ---\nclass ProductSerializer(DynamicFieldsMixin, serializers.ModelSerializer):\n    class Meta:\n        model = Product\n        fields = ['id', 'name', 'description', 'price', 'is_available']\n\n# --- DRF ViewSet ---\nclass ProductViewSet(viewsets.ModelViewSet):\n    queryset = Product.objects.all()\n    serializer_class = ProductSerializer\n\n# To use this, configure Django URL patterns to include ProductViewSet.\n# Example API request with dynamic fields:\n# GET /api/products/?fields=id,name,price\n# GET /api/products/?omit=description,is_available","lang":"python","description":"To use `drf-dynamic-fields`, inherit `DynamicFieldsMixin` in your Django REST Framework serializer. The mixin will automatically check for `fields` or `omit` query parameters in the request context and adjust the serializer's output accordingly. Ensure your view passes the request context to the serializer."},"warnings":[{"fix":"Always ensure the serializer is initialized with `context={'request': request}`. DRF's `APIView` and `GenericAPIView` subclasses handle this automatically, but custom views or direct instantiations need explicit context passing.","message":"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`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Avoid providing both `fields` and `omit` query parameters in the same request to prevent ambiguity. If necessary, explicitly define a clear preference in your client-side logic.","message":"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`.","severity":"gotcha","affected_versions":"All versions"},{"fix":"For optimal performance, combine dynamic field selection with queryset optimizations like `only()` or `defer()` (for Django ORM) or `select_related()` / `prefetch_related()` when appropriate, to ensure your database queries only fetch necessary data.","message":"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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-17T00:00:00.000Z","next_check":"2026-07-16T00:00:00.000Z","problems":[{"fix":"Ensure your view passes the request object in the serializer context, e.g., `serializer = MySerializer(instance, context={'request': request})`.","cause":"The `DynamicFieldsMixin` tries to access `self.context['request']` but the serializer was instantiated without the request in its context.","error":"KeyError: 'request'"},{"fix":"Verify 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.","cause":"The `DynamicFieldsMixin` is either not inherited by the serializer, or the `request` object is missing from the serializer's context.","error":"Serializer output does not reflect `fields` or `omit` query parameters."},{"fix":"Check 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.","cause":"A field name specified in the `fields` or `omit` query parameter does not correspond to an actual field defined on the serializer.","error":"ValueError: Field 'invalid_field_name' does not exist on serializer 'MySerializer'"}]}