在 Django Rest Framework GET 调用中自定义 JSON 输出

L. *_* W. 6 python django json django-rest-framework

我正在尝试从 MySQL 数据库中检索过滤列表。查询本身看起来不错,但返回的 JSON 显示如下:

[
{
    "id": "0038",
    "name": "Jane Doe",
    "total_hrs_per_week": 6,
    "timezone": "America/Los_Angeles"
},
{
    "id": "0039",
    "name": "John Doe",
    "total_hrs_per_week": 10,
    "timezone": "America/Los_Angeles"
}]
Run Code Online (Sandbox Code Playgroud)

当我需要构建的规范想要这个时:

{
"people":[
{
    "id": "0038",
    "name": "Jane Doe",
    "total_hrs_per_week": 6,
    "timezone": "America/Los_Angeles"
},
{
    "id": "0039",
    "name": "John Doe",
    "total_hrs_per_week": 10,
    "timezone": "America/Los_Angeles"
}]}
Run Code Online (Sandbox Code Playgroud)

这是我的序列化器

class PeopleListSerializer(serializers.ModelSerializer):
    id = serializers.CharField(source='id')
    name =serializers.CharField(source='name')
    total_hrs_per_week = serializers.IntegerField(source='total_hrs_per_week')
    timezone = serializers.CharField(source='timezone')

    class Meta:
        model = models.Person
        fields = ('id','name','total_hrs_per_week','timezone')
Run Code Online (Sandbox Code Playgroud)

知道如何以这种方式包装返回的结果吗?

编辑:

我试着把它包装在另一个像这样的序列化器中

    class PeopleListWrapperSerializer(serializers.Serializer):
        people = PeopleListSerializer(many=True)

        class Meta:
            fields = ['people']
Run Code Online (Sandbox Code Playgroud)

但这会引发以下错误:

尝试获取peopleserializer 上的字段值时出现 AttributeError PeopleListWrapperSerializer。序列化器字段可能命名不正确,并且与Person实例上的任何属性或键都不匹配。原始异常文本是:“人”对象没有属性“人”。

Rah*_*pta 6

您可以通过覆盖该list()方法来做到这一点。

class PeopleListView(ListAPIView):

    def list(self, request, *args, **kwargs):
        # call the original 'list' to get the original response
        response = super(PeopleListView, self).list(request, *args, **kwargs) 

        # customize the response data
        response.data = {"people": response.data} 

        # return response with this custom representation
        return response 
Run Code Online (Sandbox Code Playgroud)