[英]Schema for Rest Framework serializer with modified 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.