目前我在API响应中有这个格式
"inner_divertor": {
"volume": 5.2,
"volume_units": "m^2",
"volume_notes": "xyz"
},
"outer_divertor": {
"volume": null,
"volume_units": "m^3",
"volume_notes": null
}
我正在尝试添加"volume"字段,并将字段嵌套在其中。我们的目标是得到如下内容:
"inner_divertor": {
volume:{
"volume": 4.3,
"volume_units": "m^2",
"volume_notes": "xyz"
}
},
"outer_divertor": {
volume: {
"volume": null,
"volume_units": "m^3",
"volume_notes": null
}
}
以下是序列化器:
class InnerDivertorSerializer(FlexFieldsModelSerializer):
class Meta:
model = InnerDivertor
fields = ('volume', 'volume_units', 'volume_notes')
class OuterDivertorSerializer(FlexFieldsModelSerializer):
class Meta:
model = OuterDivertor
fields = ('volume', 'volume_units', 'volume_notes')
根据这个链接文档,https://pypi.org/project/drf-flex-fields/
我认为你不应该把inner_divertor
,outer_divertor
分成两个独立的类,因为它们在同一层次结构上。
不要那样做,试试这个:
class DivertorSerializer(FlexFieldsModelSerializer):
class Meta:
model = Divertor
fields = ('inner_divertor', 'outer_divertor')
expandable_fields = {
'inner_divertor': VolumnSerializer,
'outer_divertor': VolumnSerializer
}
class VolumnSerializer(FlexFieldsModelSerializer):
class Meta:
model = Volumn
fields = ('volume', 'volume_units', 'volume_notes')
更重要的是,你需要有音量和分流器model