django - Return QuerySet as JSON? -


i'm working in django 1.8 , having trouble finding modern way this.

this i've got, based on googling , this blog post:

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

however gives me 'pct' object has no attribute 'as_dict'.

surely there must neater way now?

i wondering if possible use jsonresponse frustratingly, docs give no example of how use jsonrespose queryset, must common use case. have tried this:

results = pct.objects.filter(code__startswith='a') return jsonresponse(results, safe=false) 

this gives [<pct: pct object>, <pct: pct object>] not json serializable.

simplest solution without 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 need values:

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

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


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -