如何序列化字符串列表

2024-09-30 12:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的序列化程序很容易出问题
我的看法是:

@api_view(['GET'])
def get_recipes_list(request):
    recipes = Recipe.objects.all()

    serializer = RecipeListSerializer(recipes, context={'request': request}, many=True)
    return Response(serializer.data)

我的序列化程序:

class RecipeListSerializer(serializers.Serializer):
    name = serializers.CharField()

我得到的输出:

[
    {
        "name": "Gelato1"
    },
    {
        "name": "Gelato2"
    },
]

我想要的是:

[
    'name': [
       'Gelato1',
       'Gelato2',
    ] 
]

我试过:recipes = Recipe.objects.all().values_list('name', flat=True)
所以QuerySet有一个名字列表,但我得到了一个AttributeError。 如有任何建议,我将不胜感激


Tags: name程序true序列化objectsrequestrecipeall
1条回答
网友
1楼 · 发布于 2024-09-30 12:15:35

如果使用带有平面属性的值列表,则不需要将其传递给序列化程序。对于输出,可以将结果添加到响应:

recipes =list(Recipe.objects.values_list('name', flat=True)
return Response({'output':recipes})

相关问题 更多 >

    热门问题