4

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?

Dirty Penguin
  • 4,212
  • 9
  • 45
  • 69

2 Answers2

6

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

David Cain
  • 16,484
  • 14
  • 65
  • 75
2

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'
jbub
  • 2,586
  • 23
  • 23
  • 1
    I tried your suggestion but it didn't work. It looks like I have to specify the actual variable name '-order_date' instead of '-Order Date'. – Dirty Penguin Nov 04 '13 at 17:26
  • Well, you should edit your question then, you specified that the column name is "Order Date", clearly you have the "order_date" attribute in your model ... – jbub Nov 04 '13 at 17:29
  • 1
    I meant "column" as in what is rendered by the browser. Clearly I can't have spaces in variable names. – Dirty Penguin Nov 04 '13 at 17:33
  • Well you can in your database ... anyway, i think you got it working – jbub Nov 04 '13 at 17:35