我實作了對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其中的檔案中都沒有找到任何幫助。
在此先感謝您的幫助。
uj5u.com熱心網友回復:
您可以嘗試定義用于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")
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/396965.html
上一篇:Django中的查詢集
下一篇:如何檢查當前請求是否來自htmx
