Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return QuerySet as JSON?

Tags:

json

django

I'm working in Django 1.8 and having trouble finding the modern way to do this.

This is what I've got, based on Googling and this blog post:

results = PCT.objects.filter(code__startswith='a')
json_res = []
for result in results:
    json_res.append(result.as_dict())
return HttpResponse(json.dumps(json_res), content_type='application/json')

However this gives me 'PCT' object has no attribute 'as_dict'.

Surely there must be a neater way by now?

I was wondering if it was possible to use JSONResponse but frustratingly, the docs give no example of how to use JSONRespose with a queryset, which must be the most common use case. I have tried this:

results = PCT.objects.filter(code__startswith='a')
return JsonResponse(results, safe=False)

This gives [<PCT: PCT object>, <PCT: PCT object>] is not JSON serializable.

like image 953
Richard Avatar asked May 14 '15 17:05

Richard


1 Answers

Simplest solution without any additional framework:

results = PCT.objects.filter(code__startswith='a').values('id', 'name')
return JsonResponse({'results': list(results)})

returns {'results': [{'id': 1, 'name': 'foo'}, ...]}

or if you only need the values:

results = PCT.objects.filter(code__startswith='a').values_list('id', 'name')
return JsonResponse({'results': list(results)})

returns {'results': [[1, 'foo'], ...]}

like image 182
Leistungsabfall Avatar answered Sep 27 '22 17:09

Leistungsabfall