我读了一些关于此的其他帖子,一些建议涉及javascript和使用其他库。我手动快速做了一些事情,但我是Django和Python的新手,所以我很好奇这是不是一个很好的方法。
HTML
<table>
<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>
查看
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})
答案 0 :(得分:2)
对我来说很好看。我建议在视图代码中进行一次小的重构:
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(...)
答案 1 :(得分:1)
我对可排序表的第一个调用端口通常是sorttable.js(http://www.kryogenix.org/code/browser/sorttable/)
或sortable-table(http://yoast.com/articles/sortable-table/)