python - Django:django-tables2 更改默认排序行为

标签 python django django-tables2

我正在试验 django-tables2。我创建了一个显示日期列的测试站点(由 timezone.now() 创建)。默认情况下,日期顺序为最旧->最新。如果我单击列标题,日期将以相反的顺序显示(所需的默认行为)。

我试过 order_by 参数,但我做错了。我的表格.py:

class OrderTable(tables.Table):
    order_date = tables.Column(order_by=("Order Date",))

我的观点.py:

def index(request):
    table = OrderTable(Order.objects.all())
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    return render(request, 'orders_app/index.html', {'table': table})

如何订购“订购日期”列,使其显示为最新 -> 最旧?

最佳答案

只需在列名前添加一个'-' 即可颠倒顺序。您可以在初始化表时提供 order_by

def index(request):
    table = OrderTable(Order.objects.all(), order_by="-order_date")
    RequestConfig(request, paginate={"per_page": 10}).configure(table)
    return render(request, 'orders_app/index.html', {'table': table})

参见 order_by :

The default ordering. e.g. ('name', '-age'). A hyphen - can be used to prefix a column name to indicate descending order.

另请参阅 specifying alternative ordering for a column

关于python - Django:django-tables2 更改默认排序行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772023/

相关文章:

python - 在 matplotlib 中绘制数据点的计数

python - django HTTP 405 方法不允许以 html 形式出现

python - 如何在 Django-tables2 中排序

django - 如何更改 Django 表格行的颜色?

python - 如何在 FastAPI 中上传 CSV 文件并将其转换为 JSON?

python - 表格:FileNotFoundError:[Errno 2](但文件路径正确)

django - 在 Django 中使用 OSGeo4W 的 GDAL 时 libcurl.dll 出错

javascript - 使 Django 表中的行可单击

python - 为什么python3k的pyserial返回字节而python2k返回字符串?

python - heroku 限制和限制