Suresh Jaganathan
Suresh Jaganathan

Reputation: 537

Django tables2 - how to sort table column on page loading?

I'm using django tables2 to render data in table form. I want the table to be sorted by column1 as default when page loading. The sort is working on clicking the column but I want this to be sorted by default on page loading.

Upvotes: 5

Views: 3459

Answers (2)

Jieter
Jieter

Reputation: 4229

The Table constructor has an order_by-argument. You can use that to set initial ordering.

import django_tables2 as tables

class Table(tables.Table):
    first_name = tables.Column()
    last_name = tables.Column()


def view(request):
    table = Table(data, order_by='last_name')

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

This option is also available in Table's class Meta:

class Table(tables.Table):
    first_name = tables.Column()
    last_name = tables.Column()

    class Meta:
        order_by = '-last_name'  # use dash for descending order

Upvotes: 6

uajain
uajain

Reputation: 42

If your database is SQLite, try:

results = model_name.objects.extra(select={'model_field':'CAST(model_field AS INTEGER)'}).order_by('model_field')
return render(request, template_name, {"results":results})

Upvotes: -2

Related Questions