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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

My apologies. I've revised the answer, it should fit your needs.
Is it possible to do something like this with multiple values?
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'

4 Comments

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'.
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 ...
I meant "column" as in what is rendered by the browser. Clearly I can't have spaces in variable names.
Well you can in your database ... anyway, i think you got it working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.