根据值自定义drf序列化器的json输出中的键名

时间:2019-07-19 03:27:20

标签: django django-rest-framework

起初,很抱歉提出之前多次提出的问题(我很确定是)。 假设我有这种模型关系:

class Balance(models.Model):
    class Meta:
        verbose_name = u"Balance"
        verbose_name_plural = u"Balances"

    name = models.CharField(max_length=200, verbose_name=u"Currency", null=True, blank=True)
    count = models.FloatField(verbose_name=u"Count", null=True, blank=True)
    account = models.ForeignKey(Account, verbose_name='Account', on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.name

class Account(Page):
    ...

还有那些序列化器

class BalanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = accounts.Balance
    fields = ('pk', 'name', 'count')

class AccountSerializer(serializers.ModelSerializer):
    balance_set = BalanceSerializer(many=True, required=False)

    class Meta:
         model = accounts.Account
         fields = (... , balance_set )

因此帐户序列化程序向我返回json输出,如下所示:

{
*some account information*
balance_set:
   { 
   pk: 1
   name: foo,
   count: bar
   }, ...
}

但是我希望它像这样返回我balance_set:

{
    *some account information*
    balance_set:
       { 
       foo: bar,
       balanceName:balanceCount,
       }
    }

我已经在Google上搜索并查找了文档,但不知道该怎么做。

2 个答案:

答案 0 :(得分:0)

您可以覆盖序列化程序的to_representation来完成此操作

def to_representation(self, instance):
    data = super(AccountSerializer, self).to_representation(instance)
    balance_set = data.get('balance_set')
    for i in balance_set:
         foo = i.get('name')
         bar = i.get('count')
         data['balance_set'][foo] = bar      
    return data

答案 1 :(得分:0)

覆盖 to_representation() 类的 BalanceSerializer 方法

class BalanceSerializer(serializers.ModelSerializer):
    class Meta:
        model = accounts.Balance
        fields = ('pk', 'name', 'count')

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation[representation.pop('name', '')] = representation.pop('count', None)
        return representation