【问题标题】:Schema for Rest Framework serializer with modified to_representation带有修改 to_representation 的 Rest Framework 序列化程序的架构
【发布时间】: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


    【解决方案1】:

    您可以尝试定义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")
    

    【讨论】:

    • 谢谢,这是一个很好的建议!我昨天通过注释和定义字段得到了类似的东西,但source 更干净,
    猜你喜欢
    • 2015-06-29
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2022-08-22
    • 2013-04-12
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多