Django paginator in AJAX

1

I am trying to return the elements of the table professionals and the next page, both data in a JSON. The problem arises when I see the JSON that is returned: my professionals model is a string, not an array of objects. Here I leave my code:

if request.is_ajax():
    professionals = Professionals.objects.defer('id_card')
    paginator = Paginator(professionals, 2)
    page = request.GET.get('page')
    try:
        professionals = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        professionals = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        professionals = paginator.page(paginator.num_pages)

    data_response = {}
    data_response['professionals'] = serializers.serialize("json", professionals)
    data_response['next_page'] = professionals.next_page_number() if (professionals.has_next()) else -1
    return HttpResponse(json.dumps(data_response), content_type = "application/json")
    return HttpResponseNotFound('<h1>Page not found</h1>')

I would like it to be returned as currentProfessional which I did by hand to show.

Thank you very much

    
asked by Genarito 19.12.2016 в 15:01
source

1 answer

2

The django serializer, by default, returns a string, that is, what it does is generate a string with the data of the queryset or list of objects that you pass, so from python could not access it as you would as with a normal dictionary of the form:

...
print(professionals[0]['model'])
...

However, knowing that it is a string, you have to look for alternatives to pass that string to JSON, and the best way is from the front, in the method where you receive the server response by the AJAX request:

...
success: function (data) {
    // puede hacerse así si usas jQuery
    var professionals = $.parseJSON(data);
    // de lo contrario, hacer como propones
    var professionals = JSON.parse(data);
    // sigues trabajando con tus datos como un objeto de javascript
}
...

Which evaluates the string and transforms it into a javascript object, to work more comfortably

    
answered by 19.12.2016 / 15:35
source