使用DRF将两个字段映射到一个字段

时间:2017-05-17 23:38:30

标签: serialization django-rest-framework

说我有模型Team,它与PlayerStandin

有一对多的关系

我可以像这样序列化它们:

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": [...]
    }
}

1 个答案:

答案 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