说我有模型Team
,它与Player
和Standin
我可以像这样序列化它们:
class TeamSerializer(serializers.ModelSerializer):
...
players = PlayerSerializer(many=True)
standins = StandinSerializer(many=True)
class Meta:
model = Team
fields = '__all__'
因此输出将是:
{
"id": 17,
...
"players": [...],
"standins": [...]
}
我怎么能得到:
{
"id": 17,
...
"roster": {
"players": [...],
"standins": [...]
}
}
答案 0 :(得分:1)
覆盖你的sereializer上的to_representation方法:
def to_representation(self, instance):
ret = super(TeamSerializer, self).to_representation(instance)
ret['roster'] = {
'players': ret['players'],
'standins': ret['standins']
}
del ret['players']
del ret['standins']
return ret