Answer the question
In order to leave comments, you need to log in
Django response in json format?
I'm trying to send data in json format, but I get an error:
Option 1
views.py
...
ingredients = Food.objects.values_list('id', 'title').filter(title__icontains=name)
response_data = serializers.serialize('json', ingredients)
return JsonResponse(response_data)
'tuple' object has no attribute '_meta'
...
ingredients = Food.objects.values_list('id', 'title').filter(title__icontains=name)
return JsonResponse(json.dumps(ingredients), safe=True)
< QuerySet[(...)] > is not JSON serializable
Answer the question
In order to leave comments, you need to log in
The simplest solution
ingredients = Food.objects.values('id', 'title').filter(title__icontains=name)
return JsonResponse({'ingredients': list(ingredients)})
you need a JSON object or string that can be converted to JSON
https://stackoverflow.com/questions/15874233/outpu...
JsonResponse accepts dict.
Alternatively, you can try to define a function in the model that will return an object as a dict.
ingredients = map(lambda food: food.to_json(), Food.objects.values_list('id', 'title').filter(title__icontains=name))
return JsonResponse(json.dumps(ingredients), safe=True)
It's worth using the Django REST Framework in the long run: djangorestframework.org
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question