Search code examples
jsondjangodjango-haystackpaginator

Django send object as json


Is there a way to send with json (or anything else other than render) an object_list made with paginator? The browser is making a getjson jquery request and the views.py function is supposed to return the object. The reason I want to return a json object rather than render a new page is because I don't want the page to reload

The following views.py code:

searchresults = form.search()#this is a call to a haystack form template
results = Paginator(searchresults, 20)
page = results.page(1)
return HttpResponse(json.dumps(page), content_type='application/json')

Gets this error:

TypeError: <Page 1 of 1> is not JSON serializable

Solution

  • Just use django serialization https://docs.djangoproject.com/en/dev/topics/serialization/

    from django.core import serializers
    ...
    return HttpResponse(serializers.serialize("json", [q.object for q in results.page(1).object_list]), content_type='application/json')