Installation

drf-flex-fields2 is a thin extension for Django REST Framework serializers. It keeps your existing serializer design and adds three request-driven controls: expand for nested representations, fields for sparse inclusion, and omit for explicit exclusions. For behavior examples, see Usage.

Install the package from PyPI:

pip install drf-flex-fields2

Then subclass FlexFieldsModelSerializer in place of DRF’s regular ModelSerializer:

from rest_flex_fields2.serializers import FlexFieldsModelSerializer


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}),
        }

If you already have a custom serializer base class, you can instead mix in FlexFieldsSerializerMixin. See Using FlexFieldsSerializerMixin with a Custom Base for a practical integration pattern.

Optional Django settings

Runtime behavior can be customized with the REST_FLEX_FIELDS2 setting (see also API Reference for configuration constants):

REST_FLEX_FIELDS2 = {
    "EXPAND_PARAM": "expand",
    "FIELDS_PARAM": "fields",
    "OMIT_PARAM": "omit",
}

The full list of supported settings is documented in Advanced Topics.

Next steps

  • Follow Quick Start for a complete first request/response flow.

  • Read Core Concepts for the request semantics behind expand, fields, and omit.