Django-tables2不排序

问题描述 投票:3回答:3

我使用django-tables2显示数据库表。全部显示都可以,但是单击列标题不会按该列排序。标头是可点击的,但其html中没有url文本,例如:]

<div class="table-container">
<table class="paleblue"><thead><tr><th class="id orderable sortable"><a href="">ID</a>
</th><th class="orderable sortable system"><a href="">System</a></th> ...

我检查了django-tables2模板源,并且这样说:

... <a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}"> ...

我不理解。

我只能通过在view.py中设置order_by来进行排序:

class ResultsTable(tables.Table):
    class Meta:
        model = Performance
        attrs = {'class': 'paleblue'}
        order_by_field = True

def result(request, system):
    results = Performance.objects.filter(system__name=system)
    table = ResultsTable(results, order_by=('<any column name from Performance>',))
    RequestConfig(request).configure(table)
    return render_to_response('result.html', {'table': table})

但是那显然只适用于一列,我想单击列以选择要排序的列。

根据docs的理解,按列排序应该“开箱即用”,这是正确的,还是我做错了其他事情?

django django-tables2
3个回答
5
投票

经历过同样的问题,只有我错过了

django.core.context_processors.request

来自settings.py中的TEMPLATE_CONTEXT_PROCESSORS


1
投票

[经过一夜的睡眠,对代码的重新外观和django-tables2文档中的示例进行逐字比较后,找到了我自己的问题的答案。

对于我使用的结果函数:

return render_to_response('result.html', {'table': table})

如果我将其替换为:

return render(request, 'result.html', {'table': table})

按预期进行排序。不要问我为什么...


0
投票

此页面上的其他回复都指向正确的方向,但只想包含使此功能在一个地方工作所需的一切。在视图中:

  1. 定义查询集排序
  2. 将查询集传递到表实例中
  3. 在表obj上设置任何自定义项,例如默认顺序
  4. 将所有内容包装在RequestConfig中(必不可少-没有此功能,订购将不起作用!)
  5. 将完全配置的表传递到模板上下文中
# views.py
from django_tables2 import RequestConfig
...
data = MyModel.objects.all()
my_table = MySummariesTable(data)
my_table.order_by = "-name"
RequestConfig(request).configure(my_table)
ctx = {"my_table": my_table}

return render(request, "path/mytemplate.html", ctx)

如果您的任何列都需要通过外键关系进行排序,请使用例如,在表列定义中定义这些列。

col1 = tables.Column(verbose_name="Some Col", order_by="mycol.foobar.name")

© www.soinside.com 2019 - 2024. All rights reserved.