Shaping#

ADR 0036 response-shaping helpers: project() for top-level field selection (?fields=a,b) and MinimalViewMixin for the ?view=minimal response preset.

class MinimalViewMixin#

ADR 0036 ?view=minimal support for DRF views.

Mix into a view and either set minimal_fields (the projection applied to each serialized object) or override to_minimal_representation() for shapes a plain projection cannot express (for example collapsing an embedded sub-object to its id).

The view applies the shaping explicitly, immediately before building the response:

class EnrollmentViewSet(MinimalViewMixin, viewsets.ViewSet):
    minimal_fields = ("course_id", "mode", "is_active")

    def list(self, request):
        data = self.get_serializer(items, many=True).data
        return Response(self.shape_minimal(data, request))

The default response shape is returned unchanged unless the client sends ?view=minimal (both the parameter name and value are overridable via minimal_view_query_param and minimal_view_value).

is_minimal_view_requested(request=None)#

Return True when the caller asked for the minimal preset.

minimal_fields = None#

Top-level fields kept by the default to_minimal_representation(). Views that need a non-projection shape override the method instead.

minimal_view_query_param = 'view'#

Query parameter that selects the response preset.

minimal_view_value = 'minimal'#

Parameter value that selects the minimal preset.

shape_minimal(data, request=None)#

Apply the minimal representation to data when the client asked for it.

data may be one serialized object (a dict) or a list of them; the original is returned untouched when the minimal preset was not requested.

to_minimal_representation(item)#

Return the minimal representation of one serialized object.

Defaults to projecting item onto minimal_fields; raises ImproperlyConfigured when the view configured neither the fields nor an override, so a requested minimal view never silently returns the full payload.

project(data, fields)#

Return a new dict containing only the top-level keys of data named in fields.

Parameters:
  • data – a dict (typically serializer.data). Anything else is returned untouched.

  • fields – an iterable of field names, or a comma-separated string (for example the raw value of a ?fields= query parameter). Falsy → no filtering (data is returned unchanged).

Returns:

A new dict containing only the requested top-level keys, or the original data when filtering is not applicable.

Note

Only top-level keys are honoured. Dotted paths (fields=children.x) are stripped to their first segment (children) — full dotted-path traversal is intentionally not implemented, per the ADR 0036 guidance to reject silent over-fetching via that syntax.