Quick Start

This example shows a serializer that exposes a country relation by primary key unless the client explicitly asks for an expanded nested representation.

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


class PersonSerializer(FlexFieldsModelSerializer):
    class Meta:
        model = Person
        fields = ("id", "name", "country", "occupation")
        expandable_fields = {
            "country": CountrySerializer,
        }

Default response:

GET /people/142/
{
    "id": 142,
    "name": "Jim Halpert",
    "country": 1
}

Expanded response:

GET /people/142/?expand=country.states
{
    "id": 142,
    "name": "Jim Halpert",
    "country": {
        "id": 1,
        "name": "United States",
        "states": [
            {
                "id": 23,
                "name": "Ohio"
            },
            {
                "id": 2,
                "name": "Pennsylvania"
            }
        ]
    }
}

From there, continue with Usage for nested expansion, sparse fieldsets, list-view restrictions, and lazy serializer references. Then use Serializer Options for constructor and nested serializer option patterns.

If you are new to the request model, read Core Concepts first and then return to Usage. For project-level settings and queryset optimization, see Advanced Topics.