Django-rest,返回自定义的Json

问题描述 投票:0回答:1

嗨,我有用于后端查询的代码

class HexList(generics.ListCreateAPIView):
    serializer_class = HexSerializer

    def get_queryset(self):
        hex_list = Hex.objects.filter(game_id=self.kwargs['pk'])
        return hex_list

返回此Json:

[
    {
        "id": 2,
        "game_id": 0,
        "position": 3,
        "resource": "NO",
        "token": 0
    },
    {
        "id": 3,
        "game_id": 0,
        "position": 5,
        "resource": "WO",
        "token": 0
    },
    {
        "id": 4,
        "game_id": 0,
        "position": 6,
        "resource": "BR",
        "token": 4
    }
]

我希望它返回的是相同的数据,但是具有像这样的Json形状:

    "hexes":[
                {
                    "id": 2,
                    "game_id": 0,
                    "position": 3,
                    "resource": "NO",
                    "token": 0
                },
                {
                    "id": 3,
                    "game_id": 0,
                    "position": 5,
                    "resource": "WO",
                    "token": 0
                },
                {
                    "id": 4,
                    "game_id": 0,
                    "position": 6,
                    "resource": "BR",
                    "token": 4
                }
            ]
}

我已经尝试过了:

class HexList(generics.ListCreateAPIView):
    serializer_class = HexSerializer

    def get_queryset(self):
        hex_list = Hex.objects.filter(game_id=self.kwargs['pk'])
        return Response({'hexes': hex_list})

而且我收到ContentNotRenderedError异常

我该怎么办?在此先感谢

python django django-rest-framework
1个回答
0
投票
关于get_queryset方法,它应该返回要使用的查询集,而不是Response。对于Response的烦躁不安,您应该覆盖list方法。像这样的东西应该起作用,但是我没有对其进行测试。

class HexList(generics.ListCreateAPIView): serializer_class = HexSerializer def get_queryset(self): hex_list = Hex.objects.filter(game_id=self.kwargs['pk']) return hex_list def list(self, request, *args, **kwargs): hexes = self.get_queryset() serializer = self.get_serializer(hexes, many=True) return Response({'hexes': serializer.data})

热门问题
推荐问题
最新问题