Django将序列化器嵌套对象序列化为OrderedDict而不是纯JSON

时间:2017-12-03 16:56:51

标签: python django rest serializer

如何让Django序列化器将嵌套对象序列化为json而不是ordereddict?

class SummaryGroupContract:
    class Serializer(serializers.Serializer):
        total = serializers.DecimalField(max_digits = 10, decimal_places = 2)

    def __init__(self, total: Decimal):
        self.total = total

class SummaryResponse:
    class Serializer(serializers.Serializer):
        income = SummaryGroupContract.Serializer(required=False)
        expenses = SummaryGroupContract.Serializer(required=False)

    def __init__(self, income: SummaryGroupContract, expenses: SummaryGroupContract):
        self.income = income;
        self.expenses = expenses;

class SummaryViewSet(viewsets.ViewSet):
    def list(self, request):
        income = SummaryGroupContract(10.0)
        expenses = SummaryGroupContract(-90.0)

        return Response(SummaryResponse.Serializer(SummaryResponse(income, expenses)).data)

返回

{'income': OrderedDict([('total', '10.00')]), 'expenses': OrderedDict([('total', '-90.00')])}

预期

{'income': {'total': '10.00'}, 'expenses': {'total': '-90.00'}}

编辑:!!!! 我已经解决了我的问题,现在一切正常。问题是,在我的测试中,我正在检查response.data,这不是完全呈现的响应

response = self.client.get("/api/summary", format="json")
print(response.data)

相反,我切换到response.content,现在我得到了正确的json(我也误认为带有json响应的python对象)。

0 个答案:

没有答案