带分页的django排序表
我想对我的表列进行双向排序(升序和降序,按下按钮后切换)。我遇到的问题是,当我切换页面时,我的表格会出现故障 views.py带分页的django排序表,django,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
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})
以下是我在模板中显示数据的方式(为了更好地显示帖子,我缩短了类名):
公司名称
公司地址
税号
公司ID
KRS数
我的分页代码:
<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>
{%如果所有的公司都有以前的%}
{%endif%}
{%endif%}
当我切换到其他页面时{{order_by}}不会传递任何消息。另外,按下按钮后,如何使其按降序或升序排序
我想在没有外部应用程序或库的情况下进行此操作,以便更好地了解django。您忘记在上下文中添加
order\u 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>
<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})