【发布时间】:2021-12-28 17:16:15
【问题描述】:
我对序列化器的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 one 中都没有找到任何帮助。
提前感谢您的帮助。
【问题讨论】:
标签: django django-rest-framework swagger openapi