[Django]-Is not JSON serializable

72👍

It’s worth noting that the QuerySet.values_list() method doesn’t actually return a list, but an object of type django.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…

my_list = list(self.get_queryset().values_list('code', flat=True))

…then you can convert it to JSON with…

json_data = json.dumps(my_list)

You’ll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with…

response = HttpResponse(json_data, content_type='application/json')

…which you can then return from your function.

👤Aya

2👍

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

👤tuna

Leave a comment