我想以两种方式对表格列进行排序(上升和下降,按下按钮时切换)。我遇到的问题是当我切换页面时,我的表格出现故障。
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。
答案 0 :(得分:4)
您忘了在上下文中添加order_by
:
return render(request, 'companies/company_index.html',
{'all_companies': all_companies, 'order_by': order_by})
模板升序/降序:
<a href="?order_by=company_name&direction=asc">company name ascending</a>
<a href="?order_by=company_name&direction=desc">company name descending</a>
...
<a href="?page={{ all_companies.previous_page_number }}&order_by={{ order_by }}&direction={{ direction }}">previous</a>
...
<a href="?page={{ all_companies.next_page_number }}&order_by={{ order_by }}&direction={{ direction }}">next</a>
在视图中:
def company_index(request):
order_by = request.GET.get('order_by')
direction = request.GET.get('direction')
ordering = Lower(order_by)
if direction == 'desc':
ordering = '-{}'.format(ordering)
companies = Company.objects.all().order_by(ordering)
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,
'order_by': order_by, 'direction': direction})