Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a list of strings

I'm having an rather easy problem with my serializer.
My view:

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

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

My serializer:

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

Output I'm getting:

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

What I desire is:

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

I tried: recipes = Recipe.objects.all().values_list('name', flat=True)
So that the QuerySet has a list of names, but I'm getting an AttributeError. I'll be grateful for any advices.

like image 699
matixezor Avatar asked Oct 19 '25 03:10

matixezor


1 Answers

If you use values_list with flat attribute, you don't need to pass it to serializer.For your output, you can add result to Response :

recipes =list(Recipe.objects.values_list('name', flat=True)
return Response({'output':recipes})
like image 65
kamilyrb Avatar answered Oct 21 '25 18:10

kamilyrb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!