gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:42:16 26 4
gpt4 key购买 nike

我正在尝试从 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"
}]

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

{
"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"
}]}

这是我的序列化程序

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')

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

编辑:

我试过像这样将它包装在另一个序列化程序中

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

class Meta:
fields = ['people']

但这会引发以下错误:

Got AttributeError when attempting to get a value for field people on serializer PeopleListWrapperSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Person instance. Original exception text was: 'Person' object has no attribute 'people'.

最佳答案

您可以通过覆盖 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

关于python - 在 Django Rest Framework GET 调用中自定义 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37167866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com