1
我想對我的表格列進行排序(升序和降序,按下按鈕切換)。我遇到的問題是當我切換頁面時,表格出現故障。Django排序表與分頁
views.py
def company_index(request):
order_by = request.GET.get('order_by')
companies = Company.objects.all().order_by(Lower(order_by))
paginator = Paginator(companies, 10)
page = request.GET.get('page')
try:
all_companies = paginator.page(page)
except PageNotAnInteger:
all_companies = paginator.page(1)
except EmptyPage:
all_companies = paginator.page(paginator.num_pages)
return render(request, 'companies/company_index.html',
{'all_companies': all_companies})
這裏是我在我的模板(爲了更好的可視性後我縮短類名)顯示數據:
<thead>
<tr>
<th>Company name <a class="glyphicon" href="?order_by=company_name"></a></th>
<th>Company address <a class="glyphicon" href="?order_by=company_address"></a></th>
<th>Tax ID <a class="glyphicon" href="?order_by=tax_id"></a></th>
<th>Company ID <a class="glyphicon" href="?order_by=company_id"></a></th>
<th>KRS Number <a class="glyphicon" href="?order_by=KRS_number"></a></th>
</tr>
</thead>
我分頁代碼:
<ul class="pagination">
{% if all_companies.has_previous %}
<li><a href="?page={{ all_companies.previous_page_number }}&?order_by={{order_by}}">previous</a></li>
{% endif %}
<li class="disabled"><a>Page {{ all_companies.number }} of {{ all_companies.paginator.num_pages }}</a></li>
{% if all_companies.has_next %}
<li><a href="?page={{ all_companies.next_page_number }}&?order_by={{order_by}}">next</a></li>
{% endif %}
</ul>
當我切換到其他頁面時{{order_by}}傳遞無。另外,按下按鈕後,如何使其降序或升序排序?
我想在沒有外部應用程序或庫的情況下執行此操作,以便更好地理解django。