Home > Enterprise >  Schema for Rest Framework serializer with modified to_representation
Schema for Rest Framework serializer with modified to_representation

Time:12-30

I implemented a modification of the to_representation method of a serializer in order to flatten a nested relation through

class LocalBaseSerializer(serializers.ModelSerializer):
    """Helper serializer flatenning the data coming from General
    Information."""

    general_information = GeneralInformationSerializer(read_only=True)

    class Meta:
        abstract = True
        model = None
        exclude = ("id", "created_at")

    def to_representation(self, instance):
        data = super().to_representation(instance)
        general_information = data.pop("general_information")
        _ = general_information.pop("id")
        return {**general_information, **data}


class ContractReadSerializer(LocalBaseSerializer, serializers.ModelSerializer):
    class Meta:
        model = Contract
        exclude = ("created_at",)

It works as expected but, up to now, I did not manage to have the correct schema as shown from the extract below

    ContractRead:
      type: object
      description: |-
        Helper serializer flatenning the data coming from General
        Information.
      properties:
        id:
          type: integer
          readOnly: true
        general_information:
          allOf:
          - $ref: '#/components/schemas/GeneralInformation'
          readOnly: true
        beginning_of_the_contracts:
          type: string
          format: date
        termination_of_the_contracts:
          type: string
          format: date
      required:
      - beginning_of_the_contracts
      - general_information
      - id
      - termination_of_the_contracts

I did not find any help neither in DRF documentation nor in drf-spectacular one.

Thanks in advance for any help.

CodePudding user response:

You can try to define fields used in GeneralInformationSerializer and use source property eg.:

class LocalBaseSerializer(serializers.ModelSerializer):
    """Helper serializer flatenning the data coming from General
    Information."""

    some_field = serializers.CharField(source="general_information.some_field", read_only=True)
    #... some other fields like above

    class Meta:
        abstract = True
        model = None
        exclude = ("id", "created_at", "some_field")
  • Related