如何嵌套序列化器?

时间:2015-04-10 21:18:56

标签: django django-models django-rest-framework

所以我正在尝试创建一个/ api / info url,它返回我的应用程序上的各种数据。它从各种模型中提取数据并将其汇总在一个响应中。我得到了以下内容:

class SessionInfo(generics.GenericAPIView):
    def get(self, request, format=None):
        token = Token.objects.get(user=self.request.user)
        userprofile = UserProfile.objects.get(user=self.request.user)
        is_admin = self.request.user.is_staff
        is_primary_owner = userprofile.primary_owner
        managers = userprofile.reports_to.all()
        man = ["test manager 1", "test manager 2"]
        pages = Page.objects.filter(published=True, show_in_menu=True)
        pages_output = JSONRenderer().render(PageSerializer(pages).data)
        content = {
            'user': {
                "username": str(self.request.user.username),
                "first_name": str(self.request.user.first_name),
                "last_name": str(self.request.user.last_name),
                "is_admin": is_admin,
                "is_primary_owner": is_primary_owner,
                "api_token": token.key,
                "timezone": 'blalala',
                "managers": man,
            },
            'license': {
                "plan" : "gold",
                "expiry_date" : "lol",
            },
            'feature_flags': {
                'billing_test': False,
            },
            'pages': { pages_output },
        }
        return Response(content)

然而,它没有正确地序列化和呈现页面,而是将其转换为转义字符串:

{
    "feature_flags": {
        "billing_test": false
    }, 
    "user": {
        "username": "test@user.com", 
        "first_name": "Test", 
        "last_name": "User", 
        "is_admin": true, 
        "managers": [
            "test manager 1", 
            "test manager 2"
        ], 
        "api_token": "08d1a5827da9a90e7746949ffd2e69e87c51b272", 
        "timezone": "blalala", 
        "is_primary_owner": false
    }, 
    "license": {
        "expiry_date": "lol", 
        "plan": "gold"
    }, 
    "pages": [
        "[{\"id\": 1, \"title\": \"Trololol\"}, {\"id\": 2, \"title\": \"NEW pages\"}]"
    ]
}

如果我使用directuly使用pages_output = PageSerializer(pages)我得到:

<webapp_api_v1.serializers.PageSerializer object at 0x10a0d8f90> is not JSON serializable

如何使序列化程序在我构建的响应中正确嵌套?谢谢!

1 个答案:

答案 0 :(得分:0)

使用pages_output = PageSerializer(页面).data并更改&#39;页面&#39 ;: pages_output,

解决了它