I'm experimenting with django-tables2. I've created a test site that displays a column of dates (created by timezone.now()). By default, the dates are ordered Oldest->Newest. If I click on column header, the dates are displayed in reverse order (the desired default behavior).
I've played around with the order_by argument, but I'm doing something wrong. My tables.py:
class OrderTable(tables.Table):
order_date = tables.Column(order_by=("Order Date",))
My views.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})
How can I order the "Order Date" column so its displayed as Newest->Oldest?
Just prefix a '-' before the column name to reverse the order. You can supply order_by at the time of initializing the table.
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})
See order_by:
The default ordering. e.g.
('name', '-age'). A hyphen-can be used to prefix a column name to indicate descending order.
Also, see specifying alternative ordering for a column
You can either set ordering on your queryset like this:
table = OrderTable(Order.objects.order_by('-Order Date'))
or using the table object directly:
table = OrderTable(Order.objects.all())
table.order_by = '-Order Date'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With