已经搜索了许多答案,但是找不到我想要的东西:
我有两个字段(一个是外键),它将从序列化器返回如下所示的内容:
[{"prodID":"SV1", "Amount":"10"},
{"prodID":"RV1", "Amount":"37"},
{"prodID":"GG2", "Amount":"22"}]
我真正想要的(然后不必更改前端)是:
[{"SV1":"10"},
{"RV1":"37"},
{"GG2":"22"}]
使用django可以做到吗?
答案 0 :(得分:1)
您可以覆盖序列化程序的to_representation
:
class SomeSerializer(serializers.ModelSerializer):
class Meta:
model = Some
def to_representation(self, instance):
result = super(SomeSerializer, self).to_representation(instance)
new_result = {result['prodID']: result['Amount']}
return new_result