is not JSON serializable

前端 未结 2 1131
醉梦人生
醉梦人生 2020-12-03 02:27

I have the following ListView

import json
class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs)         


        
相关标签:
2条回答
  • 2020-12-03 02:49
    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.

    0 讨论(0)
  • 2020-12-03 02:55

    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.

    0 讨论(0)
提交回复
热议问题