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.
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})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.