Схема для сериализатора Rest Framework с измененным to_representation
Я реализовал модификацию метода to_representation
сериализатора, чтобы сплющить вложенное отношение через
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",)
Все работает, как ожидалось, но до сих пор мне не удалось получить правильную схему, как показано в приведенной ниже выдержке
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
Я не нашел никакой помощи ни в документации DRF, ни в drf-spectacular
одной.
Заранее спасибо за любую помощь.
Вы можете попробовать определить поля, используемые в GeneralInformationSerializer
и использовать свойство source
, например:
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")