S
S
Stanislav2017-05-30 18:44:35
Django
Stanislav, 2017-05-30 18:44:35

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)

Mistake:
'tuple' object has no attribute '_meta'

Option 2
views.py
...
ingredients = Food.objects.values_list('id', 'title').filter(title__icontains=name)
return JsonResponse(json.dumps(ingredients), safe=True)

Mistake:
< QuerySet[(...)] > is not JSON serializable

Answer the question

In order to leave comments, you need to log in

4 answer(s)
S
Stanislav, 2017-05-31
@Chebaa

The simplest solution

ingredients = Food.objects.values('id', 'title').filter(title__icontains=name)
return JsonResponse({'ingredients': list(ingredients)})

D
Dimonchik, 2017-05-30
@dimonchik2013

you need a JSON object or string that can be converted to JSON
https://stackoverflow.com/questions/15874233/outpu...

V
Vladislav, 2017-05-30
@RGV

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)

A
Anatoly Scherbakov, 2017-05-30
@Altaisoft

It's worth using the Django REST Framework in the long run: djangorestframework.org

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question