Skip to content

How to serialize a single value? #7603

@domingues

Description

@domingues

I have an endpoint that returns a list of IDs and I want to produce the following schema:

      responses:
        '200':
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/PersonId'
--
components:
  schemas:
    PersonId:
      type: string

To achieve this I created a simple FieldSerializer

class FieldSerializer(serializers.BaseSerializer):
    field: serializers.Field = None

    def __init__(self, *args, **kwargs):
        self.field = kwargs.pop('field', copy.deepcopy(self.field))
        assert self.field is not None, '`field` is a required argument.'
        assert not inspect.isclass(self.field), '`field` has not been instantiated.'
        super().__init__(*args, **kwargs)
        self.field.bind(field_name='', parent=self.parent)

    def to_internal_value(self, data):
        return self.field.to_internal_value(data)

    def to_representation(self, instance):
        return self.field.to_representation(instance)

and modified get_componetns and get_responses of AutoSchema to process BaseSerializers instead of only Serializers.

Don't know if this is the best approach... Comments are welcomed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions