I have the following ListView
import json
class CountryListView(ListView):
model = Country
def render_to_response(self, context, **response_kwargs):
return json.dumps(self.get_queryset().values_list('code', flat=True))
But I get following error:
[u'ae', u'ag', u'ai', u'al', u'am',
u'ao', u'ar', u'at', u'au', u'aw',
u'az', u'ba', u'bb', u'bd', u'be', u'bg',
u'bh', u'bl', u'bm', u'bn', '...(remaining elements truncated)...']
is not JSON serializable
Any ideas ?
Best Answer
It's worth noting that the
QuerySet.values_list()
method doesn't actually return a list, but an object of typedjango.db.models.query.ValuesListQuerySet
, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.Somewhat irritatingly, though, this object has a custom
__repr__
method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
...then you can convert it to JSON with...
You'll also have to place the resulting JSON data in an
HttpResponse
object, which, apparently, should have aContent-Type
ofapplication/json
, with......which you can then return from your function.