2016-08-19 5 views
0

名前、型、所有者などのいくつかの属性を持つモデルItemがあります。私のテンプレートでは、Itemsのリストは反復され、テーブルに表示されます。私がしたいのは、テーブルヘッドの隣のボタンがクリックされたとき、つまり名前の隣にあるボタンがクリックされたときに、テーブルの要素がアルファベット順にソートされるときに、テーブルの項目を並べ替えることです。ここに私のテンプレートは次のとおりです。テンプレートの属性別にDjangoオブジェクトをソートする

{% extends 'inventory/base.html' %} 

{% block content %} 
<a class="btn btn-default" href="{% url 'inventory:entry' %}">New Item</a> 
<script> 
    jQuery(document).ready(function($) { 
    $(".clickable-row").click(function() { 
     window.location = $(this).data("href"); 
    }); 
}); 
</script> 
{% if item_list %} 
    <table> 
     <tr> 
      <th>Name <button class="btn btn-default" href="order_table"></button></th> 
      <th>Type <button class="btn btn-default" href="order_table"></button></th> 
      <th>Barcode/Model No. <button class="btn btn-default" href="order_table"></button></th> 
      <th>Owner <button class="btn btn-default" href="order_table"></button></th> 
      <th>Edit <button class="btn btn-default" href="order_table"></button></th> 
     </tr> 
     {% for item in item_list %} 
      <tr class="clickable-row itemrow" data-href="{% url 'inventory:details' item.id %}"> 
       <td>{{ item.name }}</td> 
       <td>{{ item.itemType }}</td> 
       <td>{{ item.barcode }}</td> 
       <td>{{ item.owner.username }}</td> 
       <td><a href="{% url 'inventory:edit' item.id %}" class="btn btn-default">Edit</a></td> 
      </tr> 
     {% endfor %} 
    </table> 
{% endif %} 
{% endblock %} 
+0

さて、あなたが持っている2つのオプションが役立ちます。 Javascriptを使用して項目をページ上で直接ソートするか、sortパラメータをサーバに渡してソートしてそこにクエリをやり直してください。 –

+0

サーバにソートパラメータを渡すと、ページ全体ではなくページのテーブル部分だけをリロードできるということはありますか? – Stalfurion

+0

もちろん、Ajaxでそれを行うこともできます。 –

答えて

1

代わりにボタンのリンクを使用して、ビューにパラメータを渡す:request.GET.get('sort', 'your_default_sort')をし、それを使用する:ジャンゴで

<th><a href="{{ url('myurl') }}?sort=name">Name </a></th> 

は、使用してsortパラメータを取得することができます見ますクエリーセットを注文する。あなたはそれが機能して手動でFBVの変更を使用している場合、あなたはCBVを使用している場合だけしかしあなたのクラス

get_ordering()メソッドをオーバーライドし、それは私くらいの方がはるかに簡単datatables

のようなクライアント側のソリューションを持つだろう

希望はこれが

関連する問題