rest_flex_fields2.serializers.FlexFieldsSerializerMixin

class rest_flex_fields2.serializers.FlexFieldsSerializerMixin(*args, **kwargs)

Bases: rest_framework.serializers.Serializer

Mixin that adds sparse-fieldset and nested-expansion support to a serializer.

Accepts the fields, omit, and expand keyword arguments (names are configurable via REST_FLEX_FIELDS2 settings) both as constructor kwargs and as query-string parameters on the current request. Query parameters are only read on the root serializer; nested serializers receive their options through constructor kwargs propagated by the parent.

Declare expandable relations either on Meta.expandable_fields (preferred) or directly on expandable_fields for backwards compatibility.

expandable_fields
maximum_expansion_depth: int | None = None
recursive_expansion_permitted: bool | None = None
parent
expanded_fields = []
get_maximum_expansion_depth()

Return the effective maximum expansion depth.

Uses the serializer-level maximum_expansion_depth attribute when set, otherwise falls back to the MAXIMUM_EXPANSION_DEPTH setting.

Return type:

Optional[int]

get_recursive_expansion_permitted()

Return whether recursive expansion is allowed.

Uses the serializer-level recursive_expansion_permitted attribute when set, otherwise falls back to the RECURSIVE_EXPANSION_PERMITTED setting.

Return type:

bool

to_representation(instance)

Apply request-sourced flex-fields options once, then delegate to super.

get_fields()

Return fields after applying constructor-sourced flex-fields options.

apply_flex_fields(fields, flex_options)

Apply sparse-fieldset and expansion options to fields in place.

Removes fields that are excluded by omit or not present in fields (sparse-fieldset), then replaces fields listed in expand with their nested serializer instances. Returns the modified fields mapping.

recursive_expansion_not_permitted()

Raise a validation error indicating recursive expansion.

Override this method to raise a custom exception instead of the default ValidationError.

expansion_depth_exceeded()

Raise a validation error indicating the expansion depth limit was exceeded.

Override this method to raise a custom exception instead of the default ValidationError.