开发者

Sortable tables in Django

I read some of the other posts about this and some recommendations involved javascript and using other libraries. I did something quick by hand, but I'm new to Django and Python for that matter so I'm curious if this isn't a good way to do it.

HTML

 <table>
       开发者_Python百科 <tr>
            <td><a href="?sort=to">To</a></td>
            <td><a href="?sort=date">Date</a></td>
            <td><a href="?sort=type">Type</a></td>
        </tr>
        {% for record in records %}
        <tr><td>{{record.to}}</td><td>{{record.date}}</td><td>{{record.type}}</td></tr>
        {% endfor %}
    </table>

View

headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    if sort is not None:
        if headers[sort] == "des":
            records = Record.objects.all().order_by(sort).reverse()
            headers[sort] = "asc"
        else:
            records = Record.objects.all().order_by(sort) 
            headers[sort] = "des"
    else:
        records = Record.objects.all()
    return render_to_response("table.html",{'user':request.user,'profile':request.user.get_profile(),'records':records})


Looks good to me. I'd suggest one minor refactoring in the view code:

headers = {'to':'asc',
         'date':'asc',
         'type':'asc',}

def table_view(request):
    sort = request.GET.get('sort')
    records = Record.objects.all()

    if sort is not None:
        records = records.order_by(sort)

        if headers[sort] == "des":
            records = records.reverse()
            headers[sort] = "asc"
        else:
            headers[sort] = "des"

    return render_to_response(...)


My first port of call for sortable tables is usually sorttable.js ( http://www.kryogenix.org/code/browser/sorttable/ )

or sortable-table ( http://yoast.com/articles/sortable-table/ )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜