[Django]-Sorting queryset of search result and render back thru ajax

2👍

Your view can return a rendered snippet like which you can just render into a div on the client side

Your ajax call can look like this

function sort(){
    var sortid = $('#sort').val();
    $.ajax({
        type: "POST",
        url: "/sort/",
        data: { sortid: sortid },
    }).done(function(data){
         $('#results-div').html(data.html);
    });
}

A example view

import json
from django.shortcuts import HttpResponse
from django.template import loader, RequestContext


def my_view(request, query=None):
    # trivialized example

    sortid = request.REQUEST.get('sortid')

    # you might want to store the results into cache 
    results = MyModel.objects.filter(name__icontains=query).order_by(sortid)

    if request.is_ajax():
       t = loader.get_template('search_results.html')
       html = t.render(RequestContext({'results': results))
       return HttpResponse(json.dumps({'html': html}))
    # handle the other cases here 

inside of search_results.html you will just render the results into your table

{% for loc in results %}
<tr class="result">
    <td>
        <li>{{loc.locationname}}</li>
    </td>
    <td>    
        <li>{{loc.rating}}</li>
    </td>
    <td>
        <li>{{loc.price}}</li>
    </td>
</tr>
{% endfor %} 
👤Bulkan

1👍

 function(data){
   var tablehtml='<tbody>'
   $.each(data,function(i,res) {
       tablehtml+='<tr class="result">'+
                   '<td><li>'+res.locationname+'</li></td>'+
                   //...
       });
    $("table").html(tablehtml+'</tbody'>)
    }

nb: i’ve added tbody tag because this way of adding html is way faster if the html is wrapped in a single parent than if it is a (long) list of nodes

euh… edit but to use this you need to tell in the .ajax that you are expecting a json response (datatype:'json') which is not the case right now

also you’ll need to send a specific header(“content-type:application/json”) from the server

if you insist on sending html then parse the data on server side (wrap it) and append it at once in the callback

if you want to reconsider your sorting feature concept, if data is not so big & if you can gzip; i’d load at once all data & do the sorting in js (no more server call the feature will be way way faster for the user : little more wait on page load but instantaneous sorting then after

Leave a comment